如何从打字稿中的映射类型推断属性和值类型

问题描述 投票:0回答:1

我有一个映射类型,我想得到一个新的元组类型,例如:[属性,值],当我输入属性时,打字稿可以自动推断值的类型,但我无法解决问题,所以我寻求帮助,例如:

type DoubleTuple<T extends Record<any, any>> = T extends Record<infer P, any>
  ? [P, T[P]]
  : never;

interface ExampleModel {
  a: number;
  b: string;
}
// when i input the property 'a', number | string was inferred , but number expected
const tuple: DoubleTuple<ExampleModel> = ["a", "3"];

链接:游乐场

typescript typescript-typings
1个回答
0
投票

这里的问题是 DoubleTuple 映射类型中的 T[P] 无法正确推断属性 P 的类型。这是因为 P 被推断为 T 的键(在您的情况下为 a | b),并且 T[P ] 因此是ExampleModel['a' | 'b'],这是数字 |字符串。

要解决这个问题,您可以使用辅助函数来创建元组。此函数将根据提供的密钥强制执行正确的类型。

type DoubleTuple<T, K extends keyof T> = [K, T[K]];

function createTuple<T, K extends keyof T>(obj: T, key: K): DoubleTuple<T, K> {
    return [key, obj[key]];
}

interface ExampleModel {
    a: number;
    b: string;
}

const example: ExampleModel = {
    a: 1,
    b: "test"
};

// Now when you create the tuple, TypeScript will enforce the correct types.
const tuple = createTuple(example, 'a'); // This will be of type ['a', number]
© www.soinside.com 2019 - 2024. All rights reserved.