typescript Type guard 타입 가드
15730 단어 typescript타입가드type guardtype guard
type Guard
is a feature of TypeScript that automatically narrows down the scope of types.
A good use of typeguard is to avoid type assertion code.
✅ assertion as
export {};
function print(value: number | string) {
if (typeof value === "number") {
// as 를 사용하면 number 라는 타입을 강제하게 된다.
console.log((value as number).toFixed(2));
} else {
// as 를 사용하면 string 라는 타입을 강제하게 된다.
console.log((value as string).trim());
}
}
typescript doesn't think of a number, but the developer injects the number into typeScript.
export {};
function print(value: number | string) {
if (typeof value === "number" || typeof value === "object") {
// as 를 사용하면 number 라는 타입을 강제하게 된다.
// 만약이렇게 된다면 버그의 위험이 있다.
console.log((value as number).toFixed(2));
} else {
// as 를 사용하면 string 라는 타입을 강제하게 된다.
console.log((value as string).trim());
}
}
so i recommand to use type guard
✅ Type guard
export { };
// discriminated union
interface Person {
type: 'a';
name: string;
age: number;
}
interface Product{
type: 'b';
name: string;
price: number;
}
function print(value: Person | Product) {
if (value.type === 'a') {
console.log(value.age);
} else {
console.log(value.price);
}
}
export {};
// discriminated union
interface Person {
type: "person";
name: string;
age: number;
}
interface Product {
type: "product";
name: string;
price: number;
}
function print(value: Person | Product) {
if ("age" in value) {
// in 은 어떤 속성이 있는지 검사하는 기능이다.
console.log(value.age); // value : Person
} else {
console.log(value.price); // value : Product
}
}
✅ other Type guard
export {};
// discriminated union
interface Person {
type: "a";
name: string;
age: number;
}
interface Product {
type: "b";
name: string;
price: number;
}
interface Product2 {
type: "c";
name: string;
price2: number;
}
function print(value: Person | Product | Product2) {
switch (value.type) {
case "a":
console.log(value.age);
break;
case "b":
console.log(value.price);
break;
case "c":
console.log(value.price2);
break;
}
}
Author And Source
이 문제에 관하여(typescript Type guard 타입 가드), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@ash3767/typescript-Type-guard-타입-가드저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)