为什么打字稿省略/删除擦除符号

时间:2019-11-11 11:18:51

标签: typescript symbols mapped-types pick

首先,我是TS的新手。并尝试为自己的项目开发一些utilities。 但是当我处理类型映射时。我发现“选择/忽略/排除”和其他键入说明会删除带有符号键的字段。如此处的代码:

    interface T { a: number;[Symbol.iterator](): IterableIterator<number>; }
    type NoA=Omit<T,'a'>;

NoA将为空类型。但是我要在其中进行迭代。

为什么会这样?还有周围走走吗?

有关更多信息,我库中的相关代码为:

export type Merg<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
export type MergO<U extends object> 
  = (U extends object ? (k: U) => void : never) extends 
    (k: infer I) => void ? (I extends object ? I : object) : object;

export type Alter<T extends object, U extends object> 
  = Pick<T, Exclude<keyof T, keyof U>> & Pick<U, Extract<keyof T, keyof U>>;

export type Extra<T extends object, U extends object> = Pick<T, Exclude<keyof T, keyof U>>;
export type Common<T extends object, U extends object> = Pick<T, Extract<keyof T, keyof U>>;
export type Extend<T extends object, U extends object> = T & Omit<U, keyof T>;
export type Override<T extends object, U extends object> = Omit<T, keyof U> & U;


export type AlterOver<T extends object, U extends object, X extends object> = Alter<T, Extra<U, X>>;
export type ExtendOver<T extends object, U extends object, X extends object> = Extend<T, Extra<U, X>>;
export type OverrideOver<T extends object, U extends object, X extends object> = Override<T, Extra<U, X>>;

export type AlterLike<T extends object, U extends object, X extends object> = Alter<T, Common<U, X>>;
export type ExtendLike<T extends object, U extends object, X extends object> = Extend<T, Common<U, X>>;
export type OverrideLike<T extends object, U extends object, X extends object> = Override<T, Common<U, X>>;

基于@hackape的解决方法,新的按类型排除可能是:

export type Exclude2<T extends object, U extends object> = 
U extends { [Symbol.iterator]: any } ? Omit<T, keyof U>:
T extends { [Symbol.iterator]: infer IT } ? { [Symbol.iterator]: IT } & Omit<T, keyof U> : Omit<T, keyof U>;

1 个答案:

答案 0 :(得分:2)

就像评论中提到的@jcalz一样,Symbol.iterator被视为“众所周知的符号”,并从解析的映射类型中排除。目前,打字稿将Symbol.whatever形式的任何表达式都视为“众所周知的符号”。

解决方法:

interface T { b: boolean; a: number; [Symbol.iterator](): IterableIterator<number>; }

type Omit2<T, K extends keyof T> = T extends { [Symbol.iterator]: infer U } ? { [Symbol.iterator]: U } & Omit<T, K> : Omit<T, K>
type NoA = Omit2<T, 'a'>;