我try 将一个数组重新映射到另一个数组,结果发现direct remapgeneric remap是不同的.

generic remap按预期工作,而direct remap保留了一些来自数组类的属性,这是意想不到的.

type Input = [string, number, boolean]


// Generic remap as expected
type Remap<T> = { [I in keyof T]: T[I] }
type Output1 = Remap<Input>
//   type Output1 = [string, number, boolean].

// Direct remap but unexpected
type Output2 = { [I in keyof Input]: Input[I] }
/*   type Output2 = {
    [x: number]: string | number | boolean;
    0: string;
    1: number;
    2: boolean;
    length: 3;
    toString: () => string;
    toLocaleString: () => string;
    pop: () => string | number | boolean | undefined;
    push: (...items: (string | ... 1 more ... | boolean)[]) => number;
    ... 26 more ...;
    readonly [Symbol.unscopables]: {
        ...;
    };
} */

有没有可能在没有Array类属性的情况下直接重映射?

Playground

推荐答案

确实,对map array/tuple types to array/tuple types的支持仅在该类型是generic类型参数时才有效.这被认为是打字脚本中的错误,如第microsoft/TypeScript#27995条所述.尽管它已经存在了很长一段时间,我不确定它是否会被修复.在microsoft/TypeScript#48443中已经做了一些工作来解决这个问题,但拉请求似乎只是在悬而未决(在打印脚本5.3中).现在,您需要通过重构您的直接版本来解决这个问题

type Mapped = {[K in keyof ArrType]: ⋯K⋯}

通过使用新的泛型类型别名转换为间接版本:

type Mapper<T> = {[K in keyof T]: ⋯K⋯}
type Mapped = Mapper<ArrType>

或使用conditional type infererence声明新的泛型类型参数:

type Mapped = ArrType extends infer T ? {[K in keyof T]: ⋯K⋯} : never

Typescript相关问答推荐

类型缩小对(几乎)受歧视的unions 不起作用

使用前的组件渲染状态更新

更新:Typescript实用程序函数合并对象键路径

类型{...}的TypeScript参数不能赋给类型为never的参数''

`((PrevState:NULL)=>;NULL)|null`是什么意思?

泛型函数即使没有提供类型

泛型函数中输入参数类型的推断问题

Angular NgModel不更新Typescript

类型脚本满足将布尔类型转换为文字.这正常吗?

错误TS2403:后续变量声明必须具有相同的类型.变量';CRYPTO';的类型必须是';CRYPATO';,但这里的类型是';CRYPATO';

部分更新类型的类型相等

使用2个派生类作为WeakMap的键

寻址对象中路径的泛型类型

Typescript 中相同类型的不同结果

类型与泛型抽象类中的类型不可比较

对有效枚举值的常量字符串进行常规判断

我不明白使用打字脚本在模板中展开参考

打字错误TS2305:模块常量没有导出的成员

在TypeScript中,如何通过一系列过滤器缩小类型?

两个接口的TypeScript并集,其中一个是可选的