IT이야기

TypeScript의 재귀 부분

cyworld 2022. 3. 8. 21:59
반응형

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

반응형