programing

TypeScript: 유형/감축 유형에서 키를 제거합니다.

telecom 2023. 3. 26. 09:39
반응형

TypeScript: 유형/감축 유형에서 키를 제거합니다.

.ExcludeCart<T>T, 특정 키는 (이 경우)로)를 cart가 삭제되었습니다).을 사용하다예를 예어들, so so so so,ExcludeCart<{foo: number, bar: string, cart: number}>{foo: number, bar: string}TypeScript 서 type type type type type type type type type type type type type type type type type type type type type type type type?

내가 잘못 짚었을 경우를 대비해서 이렇게 하고 싶은 이유는 다음과 같다. JavaScript 를 TypeScript로 TypeScript는 「JavaScript」를 .cartify의 React를 합니다.Inner 컴포넌트 클래스 른른 another and another another another another another클래스를 합니다.Wrapper.

Inner을 한다cart'0' 입니다. WrappercartClient소품(소품)을 데 되는 소품cart건 to에 Inner) ) 、 ) that that that that that that that that that 。Inner받아들인다(제외) cart.

말해, 내가 어떻게 해야 할지 , 는 어떻게 정의해야 할지 알게 될 것이다.ExcludeCart , 이이기사 , , , , , , , 。

function cartify<P extends {cart: any}>(Inner: ComponentClass<P>) : ComponentClass<ExcludeCart<P> & {cartClient: any}>

TypeScript 3.5 업데이트: 유틸리티 유형을 사용할 수 있게 되었습니다.사용 예시는 Mathias의 답변을 참조하십시오.


오래된 답변: TypeScript 2.8 및의 도입으로 다음과 같이 기술할 수 있게 되었습니다.

type Without<T, K> = {
    [L in Exclude<keyof T, K>]: T[L]
};

또는 다음과 같이 보다 간결하게 설명할 수 있습니다.

type Without<T, K> = Pick<T, Exclude<keyof T, K>>;

사용법에 따라 다음과 같이 쓸 수 있습니다.

type ExcludeCart<T> = Without<T, "cart">;

이 문제는 올바르게 해결되었지만, TypeScript 3.5가 유형을 추가했다는 점을 지적하고 싶습니다.

type NoCart = Omit<{foo: string, bar: string, cart: number}, "cart">;

, 「」가 .{foo: string, bar: string}discloss.discloss.

내장된 감산 타입은 없지만, 현재 다음과 같이 해킹할 수 있습니다.

type Sub0<
    O extends string,
    D extends string,
> = {[K in O]: (Record<D, never> & Record<string, K>)[K]}

type Sub<
    O extends string,
    D extends string,
    // issue 16018
    Foo extends Sub0<O, D> = Sub0<O, D>
> = Foo[O]

type Omit<
    O,
    D extends string,
    // issue 16018
    Foo extends Sub0<keyof O, D> = Sub0<keyof O, D>
> = Pick<O, Foo[keyof O]>

질문의 경우 다음을 수행합니다.

type ExcludeCart<T> = Omit<T, 'cart'>

TypeScript > = 2.6을 사용하면 다음과 같이 단순화할 수 있습니다.

/**
 * for literal unions
 * @example Sub<'Y' | 'X', 'X'> // === 'Y'
 */
export type Sub<
    O extends string,
    D extends string
    > = {[K in O]: (Record<D, never> & Record<string, K>)[K]}[O]

/**
 * Remove the keys represented by the string union type D from the object type O.
 *
 * @example Omit<{a: number, b: string}, 'a'> // === {b: string}
 * @example Omit<{a: number, b: string}, keyof {a: number}> // === {b: string}
 */
export type Omit<O, D extends string> = Pick<O, Sub<keyof O, D>>

운동장에서 그것을 시험하다.

이 결과를 얻을 수 있는 또 다른 매우 간단한 방법이 있다

타이프스크립트에 타입을 조합할 때는 타입 "never"가 모든 것에 우선합니다.

유형을 간단하게 작성할 수 있습니다.

type noCart<T> = T & {cart : never}

또는 유형을 생성하지 않고

function removeCart<T>(obj : T) : T & {cart : never} {
    if("cart" in obj) {
        delete (obj as T & {cart : any}).cart;
    }
    return <T & {cart : never}> obj;
}

이는 Adrian의 솔루션보다는 덜 일반적이지만 복잡성이 필요하지 않을 때는 조금 더 단순합니다.

업데이트: 이 질문에 대한 해답은 위의 Adrian의 답변을 참조하십시오.아직 유용한 링크가 포함되어 있기 때문에 여기에 답변을 남겼습니다.


이 기능에 대한 다양한 오래된 요구('외부 섹션' 유형, 감산 유형)가 있지만 실제로 처리된 요청은 없습니다.

최근 매핑된 타입을 추가하여 다시 물어보니 앤더스는 일반적인 감산 타입 연산자를 만들 계획은 없지만, 아마도 이 제안서처럼 보이는 보다 제한적인 버전이 구현될 것이라고 말했습니다.

저는 개인적으로 React와 함께 작업할 때 당신과 비슷한 상황에 처했고, 안타깝게도 좋은 해결책을 찾지 못했습니다.간단한 경우, 다음과 같은 방법으로 문제를 해결할 수 있습니다.

interface BaseProps {
    foo: number;
    bar: number;
}

interface Inner extends BaseProps {
    cart: Cart;
}

interface Wrapper extends BaseProps {
    cartClient: Client;
}

하지만 전 이게 의미적 남용이라는 걸 거의 발견했어요extends키워드를 지정합니다.그리고 물론, 만약 당신이 오타를 통제하지 않는다면Inner또는BaseProps그럼 안 되겠네요

예를 들어 Exclude Cart <{foo: number, bar: string, cart: number}>는 {foo: number, bar: string}이 됩니다.

Exclude 구문을 사용하여 이 작업을 직접 수행할 수 있습니다.

Exclude<{foo: number, bar: string, cart: number}, { cart: number}>

언급URL : https://stackoverflow.com/questions/41476063/typescript-remove-key-from-type-subtraction-type

반응형