유형에서 단일 속성을 제외하고 싶습니다. 어떻게해야합니까?
예를 들어 나는
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 유형의 올바른 구현입니다. […] 우리는 Omit 타입을 사소하게 작성했기 때문에 포함시키지 않았다
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; }
작동하지만 더 나은 솔루션을 보게되어 기쁩니다.
답변
라이브러리를 사용하려면 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
Typescript 3.5부터 생략 도우미가 포함됩니다. TypeScript 3.5 RC-생략 도우미 유형
직접 사용할 수 있으며 업데이트 할 때 Omit 도우미에 대한 고유 한 정의를 제거해야합니다.
답변
에서 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);
