front/ts
[타입스크립트] 타입의 모든 프로퍼티를 Optional로 바꾸는 타입
juniKang
2022. 7. 19. 17:44
타입스크립트에서는 타입으로 타입을 조작할 수 있다.
제네릭을 사용해서 들어온 타입의 프로퍼티를 모두 optional로 바꾸는 타입을 만들어보자.
type PropertyToOptional<Type> = {
[Property in keyof Type]?:Type[Property];
};
타입을 해석하기 위해 사용 예를 보자
HTMLInputElement {
accept: string;
align: string;
alt: string;
autocomplete: string;
... 355 more ...;
}
type OptionalInputElement = PropertyToOptional<HTMLInputELement>;
OptionalInputElement {
accept?: string | undefined;
align?: string | undefined;
alt?: string | undefined;
autocomplete?: string | undefined;
... 355 more ...;
}
HTMLInputELement 타입에 사용하면 모든 프로퍼티가 optional로 바뀌는 것을 볼 수 있다. 이렇게 모든 프로퍼티를 Optional로 바꾸면, 아래코드처럼, HTMLInputElement의 355개가 넘는 프로퍼티를 모두 정의하지 않고도 인스턴스화해서 사용할 수 있다.
const element: OptionalInputElement = {}
element.min = "2"; // 자동완성이 가능하고, 주석도 볼 수 있다.
이제 위에 나왔던 타입을 해석해보자.
type PropertyToOptional<Type> = {
[Property in keyof Type]?:Type[Property];
};
1. 제네릭<Type>에 HTMLInputElement 이 들어온다.
type PropertyToOptional = {
[Property in keyof HTMLInputElement]?:HTMLInputElement[Property];
};
2. in keyof 가 HTMLInputElement의 프로퍼티의 키값을 순회하며 넣어준다.
type PropertyToOptional = {
accept?: HTMLInputElement[accept];
align?: HTMLInputElement[align];
alt?: HTMLInputElement[alt];
autocomplete?: HTMLInputElement[autocomplete];
... 355 more ...;
};
이렇게 모든 프로퍼티에 optional (?) 이 붙어서 리턴된다.