반응형
유형 스크립트에서 최소/최대 길이의 문자열 유형 선언
문서를 살펴본 결과 문자열 데이터 유형의 최소/최대 길이에 대한 검사를 직접 입력할 수 있는 방법은 없는 것 같습니다.
그런데 문자열 길이가 주어진 경계와 일치하는지 확인할 수 있도록 일부 사용자 정의 유형을 사용하여 문자열 데이터 유형을 선언하는 방법이 있습니까?
유형 생성자와 "팬텀 유형"(여기에서 이에 대한 좋은 기사 읽기)을 사용하면 유형을 값에 직접 할당할 수 없습니다.
다음은 예입니다.StringOfLength<Min,Max>다음 기법을 사용하여 입력합니다.
type StringOfLength<Min, Max> = string & {
min: Min;
max: Max;
StringOfLength: unique symbol // this is the phantom type
};
// This is a type guard function which can be used to assert that a string
// is of type StringOfLength<Min,Max>
const isStringOfLength = <Min extends number, Max extends number>(
str: string,
min: Min,
max: Max
): str is StringOfLength<Min, Max> => str.length >= min && str.length <= max;
// type constructor function
export const stringOfLength = <Min extends number, Max extends number>(
input: unknown,
min: Min,
max: Max
): StringOfLength<Min, Max> => {
if (typeof input !== "string") {
throw new Error("invalid input");
}
if (!isStringOfLength(input, min, max)) {
throw new Error("input is not between specified min and max");
}
return input; // the type of input here is now StringOfLength<Min,Max>
};
// Now we can use our type constructor function
const myString = stringOfLength('hello', 1, 10) // myString has type StringOfLength<1,10>
// the type constructor fails if the input is invalid
stringOfLength('a', 5, 10) // Error: input is not between specified min and max
// The phantom type prevents us from assigning StringOfLength manually like this:
const a: StringOfLength<0, 10> = 'hello' // Type '"hello"' is not assignable to type { StringOfLength: unique symbol }
여기에는 다음과 같은 잘못된 유형을 만드는 것을 막을 수 없는 몇 가지 제한이 있습니다.StringOfLength<-1, -300>하지만 런타임 검사를 추가할 수 있습니다.min그리고.max에 전달된 값stringOfLength생성자 함수가 유효합니다.
편집: 이 기술은 이제 유형 스크립트에서 "브랜드 유형"으로 더 일반적으로 알려져 있습니다.
언급URL : https://stackoverflow.com/questions/51813272/declaring-string-type-with-min-max-length-in-typescript
반응형
'code' 카테고리의 다른 글
| C/Unix에 대한 인수 구문 분석 도우미 (0) | 2023.06.07 |
|---|---|
| 유니언 유형을 유형 스크립트에서 열거형으로 변환하는 방법은 무엇입니까? (0) | 2023.06.07 |
| MariaDB 이름 길이 가져오기 오류 트리거 (0) | 2023.06.07 |
| Oracle PL/SQL에서 숫자 배열을 선택하는 방법은 무엇입니까? (0) | 2023.06.07 |
| Firebase 클라우드 기능: onRequest와 onCall의 차이 (0) | 2023.06.07 |