code

유형에서 속성 제외

codestyles 2020. 8. 14. 07:46
반응형

유형에서 속성 제외


유형에서 단일 속성을 제외하고 싶습니다. 어떻게 할 수 있습니까?

예를 들어

interface XYZ {
  x: number;
  y: number;
  z: number;
}

그리고 나는 재산 z제외하고 싶다.

type XY = { x: number, y: number };

3.5 이상의 TypeScript 버전

TypeScript 3.5에서는 Omit유형이 표준 라이브러리에 추가되었습니다. 사용 방법은 아래 예를 참조하십시오.

3.5 미만의 TypeScript 버전

TypeScript 2.8에서는 Exclude표준 라이브러리에 유형이 추가되어 생략 유형을 다음과 같이 간단하게 작성할 수 있습니다.

type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>

2.8 이하의 TypeScript 버전

Exclude2.8 이하 버전 에서는 유형을 사용할 수 없지만 위와 동일한 종류의 정의를 사용하기 위해 대체를 만들 수 있습니다. 그러나이 대체는 문자열 유형에서만 작동하므로 Exclude.

// Functionally the same as Exclude, but for strings only.
type Diff<T extends string, U extends string> = ({[P in T]: P } & {[P in U]: never } & { [x: string]: never })[T]
type Omit<T, K extends keyof T> = Pick<T, Diff<keyof T, K>>

사용중인 해당 유형의 예 :

interface Test {
    a: string;
    b: number;
    c: boolean;
}

// Omit a single property:
type OmitA = Omit<Test, "a">; // Equivalent to: {b: number, c: boolean}

// Or, to omit multiple properties:
type OmitAB = Omit<Test, "a"|"b">; // Equivalent to: {c: boolean}

typescript 2.8에서는 새로운 내장 Exclude유형을 사용할 수 있습니다 . 2.8 릴리스 노트는 실제로는 '미리 정의 된 조건 유형 "이 언급 :

참고 : 제외 유형은 여기에 제안 된 Diff 유형의 적절한 구현입니다. [...] 간단하게 작성 되었기 때문에 생략 유형을 포함하지 않았습니다 Pick<T, Exclude<keyof T, K>>.

이것을 예제에 적용하면 XY 유형은 다음과 같이 정의 할 수 있습니다.

type XY = Pick<XYZ, Exclude<keyof XYZ, "z">>

일부 변수를 선언하고 확산 연산자를 사용하여 유형을 추론하는 솔루션찾았습니다 .

interface XYZ {
  x: number;
  y: number;
  z: number;
}

declare var { z, ...xy }: XYZ;

type XY = typeof xy; // { x: number; y: number; }

작동하지만 더 나은 솔루션을 보니 기쁠 것입니다.


타이프 스크립트 3.5

Typescript 3.5부터 생략 도우미가 포함됩니다. TypeScript 3.5 RC-생략 도우미 유형

직접 사용할 수 있으며 업데이트 할 때 생략 도우미에 대한 자체 정의를 제거해야합니다.


라이브러리 사용을 선호하는 경우 ts-essentials를 사용하십시오 .

import { Omit } from "ts-essentials";

type ComplexObject = {
  simple: number;
  nested: {
    a: string;
    array: [{ bar: number }];
  };
};

type SimplifiedComplexObject = Omit<ComplexObject, "nested">;

// Result:
// {
//  simple: number
// }

// if you want to Omit multiple properties just use union type:
type SimplifiedComplexObject = Omit<ComplexObject, "nested" | "simple">;

// Result:
// { } (empty type)

추신 : 당신은 거기에서 다른 많은 유용한 것들을 찾을 것입니다;)


에서 3.5 타이프 라이터 :

interface TypographyProps {
    variant: string
    fontSize: number
}

type TypographyPropsMinusVariant = Omit<TypographyProps, "variant">

나는 그것을 좋아한다 :

interface XYZ {
  x: number;
  y: number;
  z: number;
}
const a:XYZ = {x:1, y:2, z:3};
const { x, y, ...last } = a;
const { z, ...firstTwo} = a;
console.log(firstTwo, last);

참고 URL : https://stackoverflow.com/questions/48215950/exclude-property-from-type

반응형