programing

문자열 리터럴 유형에 대한 TypeScript 배열

telecom 2023. 3. 31. 21:34
반응형

문자열 리터럴 유형에 대한 TypeScript 배열

현재 문자열 배열과 동일한 문자열을 포함하는 문자열 리터럴 유니언 유형이 모두 있습니다.

const furniture = ['chair', 'table', 'lamp'];
type Furniture = 'chair' | 'table' | 'lamp';

어플리케이션에 둘 다 필요하지만 코드를 드라이 상태로 유지하려고 합니다.그럼 둘 중 하나를 추론할 수 있는 방법이 있을까요?

제가 기본적으로 하고 싶은 말은type Furniture = [any string in furniture array]중복된 문자열은 없습니다.

TypeScript 3.4 이상

TypeScript version 3.4 has introduced so-called **const contexts**, which is a way to declare a tuple type as immutable and get the narrow literal type directly (without the need to call a function like shown below in the 3.0 solution).

이 새로운 구문을 사용하면 다음과 같은 간결한 솔루션을 얻을 수 있습니다.

const furniture = ['chair', 'table', 'lamp'] as const;
type Furniture = typeof furniture[number];

새로운 콘텍스트에 대한 자세한 내용은 이 PR릴리즈 노트를 참조하십시오.

TypeScript 3.0 이상

일반적인 휴식 매개변수를 사용하여 정확하게 추론할 수 있는 방법이 있다.string[]문자 그대로의 튜플 타입으로 만들고 리터럴의 결합 타입을 얻습니다.

그건 이런 식이다:

const tuple = <T extends string[]>(...args: T) => args;
const furniture = tuple('chair', 'table', 'lamp');
type Furniture = typeof furniture[number];

일반 휴식 매개 변수에 대한 자세한 정보

이 답변은 최신이 아닙니다.@ggradnig의 답변을 참조하십시오.

최적의 회피책:

const furnitureObj = { chair: 1, table: 1, lamp: 1 };
type Furniture = keyof typeof furnitureObj;
const furniture = Object.keys(furnitureObj) as Furniture[];

이상적으로는 다음과 같은 작업을 수행할 수 있습니다.

const furniture = ['chair', 'table', 'lamp'];
type Furniture = typeof furniture[number];

아쉽게도 오늘furniture로 추측되다string[]즉,Furniture이제 또한string.

수동 주석을 사용하여 입력 내용을 리터럴로 강제할 수 있지만 다음과 같이 중복됩니다.

const furniture = ["chair", "table", "lamp"] as ["chair", "table", "lamp"];
type Furniture = typeof furniture[number];

TypeScript 문제 #10195는 TypeScript에 목록을 정적 태플로 추론할 필요가 있음을 암시하는 기능을 추적합니다.string[]그래서 아마 미래에는 이것이 가능할 것이다.

typescript 3.4에서 가장 쉬운 것: (TypeScript 3.4에서 Constract 아사션이 추가되었습니다)

const furniture = ["chair", "table", "lamp"] as const;
type Furniture = typeof furniture[number]; // "chair" | "table" | "lamp"

https://stackoverflow.com/a/55505556/4481226 도 참조해 주세요.

또는 오브젝트에 다음 키가 있는 경우 유니언으로 변환할 수도 있습니다.

const furniture = {chair:{}, table:{}, lamp:{}} as const;
type Furniture = keyof typeof furniture; // "chair" | "table" | "lamp"

제가 제안하고 싶은 유일한 조정은,const다음과 같은 유형의 호환성을 보장합니다.

type Furniture = 'chair' | 'table' | 'lamp';

const furniture: Furniture[] = ['chair', 'table', 'lamp'];

배열에서 철자 오류가 발생하거나 알 수 없는 항목을 추가할 경우 경고가 표시됩니다.

// Warning: Type 'unknown' is not assignable to furniture
const furniture: Furniture[] = ['chair', 'table', 'lamp', 'unknown'];

이것이 도움이 되지 않는 유일한 경우는 어레이에 값 중 하나가 포함되어 있지 않은 경우입니다.

언급URL : https://stackoverflow.com/questions/44497388/typescript-array-to-string-literal-type

반응형