带有签名的打字稿箭头函数接受错误的参数
Typescript arrow function with signature accepts wrong parameter
考虑类型:
type GenericFunction = <T>(props: Array<T>) => void
和箭头函数:
const test: GenericFunction = <X>(props: X) => {
let dd: X }
为什么 test
函数接受 X
作为参数,尽管类型 GenericFunction
定义了 Array<T>
作为参数?
X
的类型满足 GenericFunction
的签名,这就是为什么编译器不会给出错误的原因。现在只有一个隐式约束 X
必须是数组类型。
仅当您为 X
添加与此隐式约束冲突的约束时,您才会收到错误消息:
// this gives a compile error
const test: GenericFunction = <X extends number>(props: X) => {};
考虑类型:
type GenericFunction = <T>(props: Array<T>) => void
和箭头函数:
const test: GenericFunction = <X>(props: X) => {
let dd: X }
为什么 test
函数接受 X
作为参数,尽管类型 GenericFunction
定义了 Array<T>
作为参数?
X
的类型满足 GenericFunction
的签名,这就是为什么编译器不会给出错误的原因。现在只有一个隐式约束 X
必须是数组类型。
仅当您为 X
添加与此隐式约束冲突的约束时,您才会收到错误消息:
// this gives a compile error
const test: GenericFunction = <X extends number>(props: X) => {};