typescript
22.02.18 interface extends 안될 때, Omit
슈팅스타제제
2022. 2. 20. 15:39
보통 타입스트립트의 type을 지정해줄 때 인터페이스를 정의한 후 그 안에 모든 타입을 넣어준다.
그런데 그 인터페이스에서 어떤 변수 하나의 데이터를 정제해서 타입을 다르게 다시 정의하고 싶은 경우나
인터페이스의 어떤 변수를 제외하고 다른 변수들을 추가하고 싶을 때는
전에 썼던 인터페이스 정의 코드를 다시 복붙해서 쓰기에는 하드코딩이라 좀 망설여진다...
만약에 이런 타입 정의 인터페이스가 있다고 하자.
interface Data {
id: number
name: string
place: string[]
}
place 데이터의 타입을 string[]에서 그냥 string 으로 바꿔서 다시 인터페이스
interface DataResult extends Data
처음에 나는
// 이렇게 하면 extends 옵션을 쓸 수 없다는 타입 에러가 뜸.
interface DataResult extends Data {
id: number
name: string
place: string
}
이라고 했지만 extends 로 인터페이스를 상속해주면 그 안의 속성의 타입을 변경할 수는 없었다.
그래서 Omit 으로 해당 타입을 빼고 인터페이스를 다시 정의하는 방법을 사용했다.
// Data 인터페이스에서 place 속성을 제외한 것으로 AnotherData를 재정의
type AnotherData = <Omit Data, 'place'>
그거를 그냥 이제 이렇게 쓰면 된다.
interface DataResult extends Omit<Data, 'a'> {
id: number
name: string
place: string
}
참고문서링크:
https://stackoverflow.com/questions/48215950/exclude-property-from-type
Exclude property from type
I'd like to exclude a single property from the type. How can I do that? For example I have interface XYZ { x: number; y: number; z: number; } And I want to exclude property z to get type XY ...
stackoverflow.com