programing

타이프스크립트를 사용하여 특정 길이의 문자열을 선언하려면 어떻게 해야 합니까?

instargram 2023. 7. 6. 21:48
반응형

타이프스크립트를 사용하여 특정 길이의 문자열을 선언하려면 어떻게 해야 합니까?

예를 들어 ISO 국가 코드에 사용할 수 있는 2자 길이의 문자열입니다.

저는 구글을 사용하여 문서를 살펴보았지만 답을 찾을 수 없습니다.

문자열 길이를 형식으로 지정할 수 없습니다.

국가 코드 목록이 유한한 경우 문자열 리터럴 유형을 작성할 수 있습니다.

type CountryCode = 'US' | 'CN' | 'CA' | ...(lots of others);

실제로 할 수 있습니다.

// tail-end recursive approach: returns the type itself to reuse stack of previous call
type LengthOfString<
  S extends string,
  Acc extends 0[] = []
> = S extends `${string}${infer $Rest}`
  ? LengthOfString<$Rest, [...Acc, 0]>
  : Acc["length"];

type IsStringOfLength<S extends string, Length extends number> = LengthOfString<S> extends Length ? true : false

type ValidExample = IsStringOfLength<'json', 4>
type InvalidExapmple = IsStringOfLength<'xml', 4> 

덕분에.

학습해야 할 몇 가지 흥미로운 기술인 유형 생성자와 팬텀 유형을 사용하여 이를 달성할 수 있습니다.여기서 비슷한 질문에 대한 제 대답을 볼 수 있습니다.

언급URL : https://stackoverflow.com/questions/45699053/how-do-i-declare-a-string-that-is-of-a-specific-length-using-typescript

반응형