반응형
Typescript 하면서 undefined를 지정하는 방법은 2가지가 있다.
// Optional Parameters로 지정하는 방법
interface Fruit {
cost?: number
}
// Union으로 지정하는 방법
interface Fruit {
cost: number | undefined
}
2개의 방법 중에서 한 가지 차이점이 존재한다. union으로 지정했을 때는 속성이 존재해야하고, optional parameters로 지정했을 때는 속성을 정의해주지 않아도 된다.
Union으로 정의를 했다면 다음과 같이 사용하면 에러가 발생한다.
// Union으로 지정하는 방법
interface Fruit {
cost: number | undefined
}
// Property 'cost' is missing in type '{}' but required in type 'Fruit'.
const x: Fruit = {};
// Good!
const x: Fruit = { cost: undefined };
Optional Parameters로 정의했다면 다음과 같이 사용할 수 있다.
// Optional Parameters 지정하는 방법
interface Fruit {
cost?: number
}
// Good!
const x: Fruit = {};
// Good!
const x: Fruit = { cost: undefined };
Reference
반응형
'Project 하면서 알아가는 것들' 카테고리의 다른 글
IoC, DI, DPI 확실히 개념 잡기 (0) | 2023.11.12 |
---|---|
REST API 확실히 개념 잡기 (0) | 2023.11.02 |
백엔드에서 이미지 업로드는 어떻게 하면 좋을까? (6) | 2023.11.01 |
[JWT] Access Token과 Refresh Token 그리고 RTR 기법에 대해서 알아보자. (0) | 2023.01.15 |
[NodeJS] Typescript EsLint 및 Prettier 적용하기 (0) | 2023.01.10 |