【发布时间】:2020-03-11 10:54:23
【问题描述】:
在下面的代码中,我将函数 doSomething 的类型定义为这种类型:(value: User) => User
奇怪的是,当将返回类型错误的函数分配给 doSomething 时,Typescript 不会抱怨。这是为什么?
interface User {
userName: string;
}
const test: User = {
userName: 'test',
bla: '123' // OK: TS complains
}
let doSomething: (value: User) => User;
doSomething = () => { // NOK: TS is not complaining about the missing parameter
return {
userName: 'test',
bla: '123' // NOK: Why does TS not complain?
}
};
在定义回调函数的类型然后传递返回“错误”值的回调时也会发生同样的情况:
interface User {
userName: string;
}
class Test {
doSomething(callback: (value: User) => User): void {}
}
const test = new Test();
test.doSomething(() => { // NOK: TS is not complaining about the missing parameter
return {
userName: 'test',
bla: '123' // NOK: Why does TS not complain?
}
})
查看 stackblitz 上的示例:https://stackblitz.com/edit/typescript-callback-2
【问题讨论】:
-
Typescript 不会对对象文字以外的任何内容进行过多的属性检查,这是设计使然。
-
Nice JS forEach 示例:
forEach(callback: (element?: T, index?: number, array?: T[]))这说明跳过参数非常好。
标签: typescript