React & TypeScript/TypeScript
[TypeScript] as 사용에 대한 이해 (feat. Type Assertions)
yoonjong Park
2022. 12. 27. 10:10
찾게된 이유 & 해결
...
// 에러 상황
data: data?.map(price => Number(price.close)),
...
// 발생된 에러
TS2769: No overload matches this call.
Overload 1 of 2, '(props: Props | Readonly<Props>): ReactApexChart', gave the following error.
Type '{ name: string; data: number[] | undefined; }' is not assignable to type 'number'.
Overload 2 of 2, '(props: Props, context: any): ReactApexChart', gave the following error.
Type '{ name: string; data: number[] | undefined; }' is not assignable to type 'number'.
// 해결 방법
data: data?.map(price => Number(price.close)) as number[]
객체에 위와 같이 값을 변환해서 넣었는데, typeError 가 발생했었다. as 문법을 활용해서 해결했다.
as문법을 알아보니까 좀 더 구체적인 타입을 지정할 수 있다고 한다. 공식문서를 보면, 컴파일러에게 힌트를 줘서 해결하는 형태이다.
더 구체적 or 덜 구체적으로는 변환이 가능하다. 그러나 아예 관계 없는 타입으로는 as 문법을 사용하는 것이 불가능하다.
유사한 활용 예
const myCanvas = document.getElementById("main_canvas") as HTMLCanvasElement;
const myCanvas = <HTMLCanvasElement>document.getElementById("main_canvas"); // tsx에서는 제외
const x = "hello" as number; // Error
// Conversion of type 'string' to type 'number' may be a mistake
// because neither type sufficiently overlaps with the other.
// If this was intentional, convert the expression to 'unknown' first.
const a = (expr as any) as T; // 가능
Keyword
Type Assertions (타입 단언 or 타입 강제 선언 정도로 이해)
참고
https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions
Documentation - Everyday Types
The language primitives.
www.typescriptlang.org
[타입스크립트] 'is', 'as' 문법 정리
타입스크립트 초보자의 'is', 'as' 문법 정리
velog.io