-
Type NarrowingTypeScript 2023. 7. 24. 18:35
타입스크립트의 Type Narrowing에 대해 정리하였습니다.
< Introduction >
Type narrowing is when TypeScript can infer more specific types based on the variable's surrounding code.
Example)
function formatDate(date: string | number) { // date can be a number or string here if (typeof date === 'string') { // date must be a string here } }
< Type guards >
One way that TypeScript can narrow a type is with a conditional statement that checks if a variable is a specific type: This pattern is called a type guard.
Example)
type Tennis = { serve: () => void; } type Soccer = { kick: () => void; } function play(sport: Tennis | Soccer) { if ('serve' in sport) { return sport.serve(); } if ('kick' in sport) { return sport.kick(); } }: The in operator checks if a property exists on an object itself or anywhere within its prototype chain.
< Narrowing with else >
Example)
function formatPadding(padding: string | number) { if (typeof padding === 'string') { return padding.toLowerCase(); } else { return `${padding}px`; } }
< Narrowing After a Type Guard >
TypeScript can also type narrow without an else statement, provided that there’s a return statement within the type guard.
Example)
type Tea = { steep: () => string; } type Coffee = { pourOver: () => string; } function brew(beverage: Coffee | Tea) { if ('steep' in beverage) { return beverage.steep(); } return beverage.pourOver(); }: Once we encounter a return statement, the function execution stops. TypeScript then infers that the code following the conditional must be of type Coffee
'TypeScript' 카테고리의 다른 글
Advanced Object Types (0) 2023.08.09 Union Types (0) 2023.07.07 Custom Types (0) 2023.06.19 Array (0) 2023.06.06 Functions (0) 2023.05.25