【发布时间】:2020-03-23 10:39:34
【问题描述】:
我正在尝试通过提供字段名称来转换对象的某些字段,目前我写了如下内容:
interface Foo {
a: number[],
b: string[],
}
type Bar = { [T in keyof Foo] : (arg : Foo[T]) => Foo[T] }
function test<T extends keyof Foo>(field: T) {
const foo : Foo = {
a: [],
b: [],
};
const bar: Bar = {
a: arg => /* some code */ [],
b: arg => /* some code */ [],
};
foo[field] = bar[field](foo[field]);
}
但我最终在bar[field](foo[field]) 上收到以下错误消息:
Argument of type 'Foo[T]' is not assignable to parameter of type 'number[] & string[]'.
Type 'number[] | string[]' is not assignable to type 'number[] & string[]'.
Type 'number[]' is not assignable to type 'number[] & string[]'.
Type 'number[]' is not assignable to type 'string[]'.
Type 'number' is not assignable to type 'string'.
Type 'Foo[T]' is not assignable to type 'number[]'.
Type 'number[] | string[]' is not assignable to type 'number[]'.
Type 'string[]' is not assignable to type 'number[]'.
Type 'string' is not assignable to type 'number'
但是打字稿不应该“知道”相同的T、Foo[T] 和Parameters<Bar[T]> 应该是相同的吗?
【问题讨论】:
标签: typescript generics types