반응형
타이프스크립트를 사용하여 특정 길이의 문자열을 선언하려면 어떻게 해야 합니까?
예를 들어 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>
덕분에.
- https://twitter.com/trashh_dev/status/1558827043504078849
- https://twitter.com/anuraghazru/status/1558836599269445637
- https://twitter.com/CodingCarter/status/1558924142379950080
학습해야 할 몇 가지 흥미로운 기술인 유형 생성자와 팬텀 유형을 사용하여 이를 달성할 수 있습니다.여기서 비슷한 질문에 대한 제 대답을 볼 수 있습니다.
언급URL : https://stackoverflow.com/questions/45699053/how-do-i-declare-a-string-that-is-of-a-specific-length-using-typescript
반응형
'programing' 카테고리의 다른 글
UNIX epoch를 Date 개체로 변환 (0) | 2023.07.06 |
---|---|
화면 지우기 - Oracle SQL Developer 바로 가기? (0) | 2023.07.06 |
수업을 어떻게 꾸밀까요? (0) | 2023.07.06 |
SQL Server가 데이터 유형 숫자로 변환하는 산술 오버플로 오류를 발생시키는 이유는 무엇입니까? (0) | 2023.07.06 |
Git(숫자 및 크기)의 파일 제한은 무엇입니까? (0) | 2023.07.06 |