【发布时间】:2020-08-30 05:35:00
【问题描述】:
我正在定义一个以接口为参数的通用函数。
这个接口有几个字段,其中一个是泛型参数的键。
另一个字段也采用此通用参数的键,但我想强制两者相等,而不需要用户明确指定它们。
这是一个具体而最小的例子:
// Generic interface representing the parameter of the generic function
interface Inte<DataType extends object, K extends keyof DataType = keyof DataType> {
key: K;
fn: (val: DataType[K]) => void;
}
// Define the generic function
function test<DataType extends object>(arg: Inte<DataType>);
// Testing interface
interface Base {
first: string;
second: number;
}
// Testing function call
test<Base>({
key: "first",
fn: (val: number) => {}, // Error on 'fn', here
});
上面的代码在fn的定义行报错,说明参数类型(number)不能赋值给string,因为它确实推断出我的泛型接口的第二个参数K ,就像 string | number 一样,尽管 key 应该可以帮助它找到正确的类型。
整个错误是(不知道为什么它会在那里放一个随机的ReactText。也许是因为我在.tsx 文件中尝试过这个?):
Type '(val: number) => void' is not assignable to type '(val: ReactText) => void'.
Types of parameters 'val' and 'val' are incompatible.
Type 'ReactText' is not assignable to type 'number'.
Type 'string' is not assignable to type 'number'.ts(2322)
我会遇到一个错误,说参数必须是 string 而不是 number。 (如果我改成val: string,则完全没有错误。
这个问题有什么解决办法吗?我知道我可以做 "strictFunctionTypes": false 但这会削弱我的类型检查。
我很确定我可以采取一些措施来可靠地解决这个问题!
顺便说一句,如果它可能以任何方式相关,实际代码发生在 React 使用的上下文中,这意味着我无法更改泛型函数的参数,因为它是一个组件。
【问题讨论】:
标签: reactjs typescript typescript-generics