Web/TypeScript
TypeScript - is keyword
김첨지
2024. 5. 29. 19:29
type narrowing을 위한 아래와 같은 코드는 타입스크립트가 그 의도를 이해하지 못한다.
const isString = (value: any) : boolean => {
return typeof value === "string"
}
const test = (str: any) => {
if (isString(str)) {
// 'str'이 'string' 타입임을 알지 못함
str.toupperCase()
// 런타임 에러 발생
}
}
이때 함수가 boolean 값을 return 하는 경우, 리턴 타입에 is 키워드를 사용하여 해당 scope내에서 지정한 타입으로 내로잉 할 수 있다.
const isString = (value: any) : value is string => {
return typeof value === "string"
}
const test = (str: any) => {
if (isString(str)) {
// 타입스크립트는 'str'이 'string'임을 알고 있다.
str.toupperCase()
// error: Property 'toupperCase' does not exist on type 'string'.
// Did you mean 'toUpperCase'?
}
}
is는 함수가 true를 반환하는 경우 해당 스코프에서 함수에 전달된 인수가 지정한 타입임을 나타낸다.
응용
아래와 같이 고차함수(map, reducs, filter, some, every,,,)를 사용하면서 데이터를 조합할 때 타입 추론이 되지 않는 경우 is를 사용할 수 있다.
is 키워드를 사용하면 아래와 같이 명시적으로 타입을 추론시킬 수 있다.