TypeScript 型ガード例
const convertAge = (age: number | undefined): any => {
if(isAge(age)){
return age + ''; //ここのageはnumberになる
}
return age;
};
const isAge = (age: number | undefined): age is number => typeof age === 'number';
const createAge = (age: number, isEmpty: boolean) => isEmpty ? undefined : age;
const result = convertAge(createAge(40, false));
console.log(result); //'44'
最近のコメント