TypeScript 의 재귀 부분
다음과 같은 인터페이스를 가지고 있다.
export interface UserSettings
{
one: {
three: number;
four: number;
};
two: {
five: number;
six: number;
};
}
...그리고 이것을 이렇게 만들고 싶다.
export interface UserSettingsForUpdate
{
one?: {
three?: number;
four?: number;
};
two?: {
five?: number;
six?: number;
};
}
...하지만Partial<UserSettings>
다음을 생성한다.
{
one?: {
three: number;
four: number;
};
two?: {
five: number;
six: number;
};
}
모든 깊이에서 모든 속성을 선택적으로 만들기 위해 매핑된 유형을 사용할 수 있는가, 아니면 인터페이스를 수동으로 만들어야 하는가?
조건형 2.8의 착륙으로, 우리는 이제 다음과 같이 재귀적 부분형을 선언할 수 있다.
type RecursivePartial<T> = {
[P in keyof T]?:
T[P] extends (infer U)[] ? RecursivePartial<U>[] :
T[P] extends object ? RecursivePartial<T[P]> :
T[P];
};
참조:
http://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html
다음과 같은 매핑 유형을 직접 만들 수 있다.
type RecursivePartial<T> = {
[P in keyof T]?: RecursivePartial<T[P]>;
};
유감스럽게도 이것은 배열 형식 필드에서는 작동하지 않는다.
조건부 유형 매핑을 수행할 수 있는 방법, 즉 원시 유형으로 제한되는 방법이 아직 없는 것 같다.
https://github.com/Microsoft/TypeScript/pull/12114#issuecomment-259776847을 참조하십시오. 이제 가능, 다른 답변을 참조하십시오.
나는 도서관을 만들었는데, 이런 흔한 패턴/스니펫을 많이 가지고 있다.
이 경우 다음과 같이 사용할 수 있다.
import { DeepPartial } from 'tsdef';
let o: DeepPartial<{a: number}> = {};
제공된 해결책 중 어느 것도 충분하지 않다.여기에 설명이 있다.
const x: RecursivePartial<{dateValue: Date}> = {dateValue: 0}; // ja-ja-ja
의 실제 유형 위에 있는 코드:dateValue
이다RecursivePartial<Date> | undefined
어떤 가치라도 부여할 수 있는!!!예상 유형:dateValue
정의롭다Date
그러나, 규칙.T[P] extends object ? RecursivePartial<T[P]>
너무 넓어
해결책은 원시성을 분리하고 제거하는 것이다.extends object
:
export type RecursivePartial<T> = {
[P in keyof T]?:
T[P] extends Array<infer U> ? Array<Value<U>> : Value<T[P]>;
};
type AllowedPrimitives = boolean | string | number | Date /* add any types than should be considered as a value, say, DateTimeOffset */;
type Value<T> = T extends AllowedPrimitives ? T : RecursivePartial<T>;
참조URL: https://stackoverflow.com/questions/41980195/recursive-partialt-in-typescript
'IT이야기' 카테고리의 다른 글
react-native에서 'No bundle URL no present'의 의미는 무엇인가? (0) | 2022.03.09 |
---|---|
문자열 변수로 텍스트 파일을 읽고 새 줄을 분리하는 방법 (0) | 2022.03.09 |
Vuex 저장소를 교체하지 않고 Vuex 업데이트 (0) | 2022.03.08 |
그룹별 판다 비율 (0) | 2022.03.08 |
렌더 함수 외부에 있는 액세스 리액션 컨텍스트 (0) | 2022.03.08 |