IT/typescript
[Typescript] Branded type
내일은교양왕
2024. 2. 21. 22:54
개념
값이 사용되기 전에 특정 기준을 충족하는 지 확인함으로써 컴파일 오류를 발생시켜 조기에 파악하는 데 도움이 됨
입력의 유효성을 검사하는 Assertion 함수와 같이 사용할 때 유용
생성 방법
기존 타입에 readonly 속성을 추가한다.
보통 readonly 속성은 '__brand', '__kind', '__type' 으로 이름 짓는다.
type PositiveNumber = number & { __brand: 'PositiveNumber' };
function divide(a: number, b: PositiveNumber) {
return a / b;
}
const x: PositiveNumber = 10; // Error: 'number' is not assignable to 'PositiveNumber'
divide(100, x);
Assertion과 같이 사용방법
type PositiveNumber = number & { __brand: 'PositiveNumber' };
function divide(a: number, b: PositiveNumber) {
return a / b;
}
function assertPositiveNumber(x: unknown): asserts x is PositiveNumber {
if (typeof x === 'number' && x < 0) {
throw new Error('Number is not greater zero');
}
}
const x = 10;
assertPositiveNumber(x);
divide(100, x); // OK!
Improve Your Type Safety with Branded Types
Branded types in TypeScript can help catch programming errors early by ensuring that values meet certain criteria before they are used. To create a branded type, you add a readonly property to an existing type. Branded types are especially useful when comb
typescript.tv