【发布时间】:2021-11-01 00:07:42
【问题描述】:
如何让 TS 从多个参数之间的特定函数参数推断类型?
type TypeA<T extends string> = Record<T, unknown>;
type TypeB<T> = { array: T[] };
function fn<T extends string>(a: TypeA<T>, b: TypeB<T>): void {}
fn(
{
attr1: 1,
attr2: 2,
},
{
array: ["attr1"],
}
);
在此示例中,TS 抱怨第一个参数中的属性 attr2。
Argument of type '{ attr1: number; attr2: number; }' is not assignable to parameter of type 'TypeA<"attr1">'.
Object literal may only specify known properties, but 'attr2' does not exist in type 'TypeA<"attr1">'. Did you mean to write 'attr1'?ts(2345)
这意味着 T 是从数组中推断出来的,但我想要完成的是 T 从第一个参数中推断出来,这是对象的键。 T 应改为 "attr1" | "attr2"。
我该如何做到这一点?
【问题讨论】:
标签: typescript typescript-generics