问题描述
限时送ChatGPT账号..在下面的代码中,我将函数 doSomething
的类型定义为这种类型:(value: User) =>用户
In the following code I defined the type of a function doSomething
to be this type: (value: User) => User
奇怪的是,当为 doSomething
分配一个返回类型错误的函数时,Typescript 不会抱怨.这是为什么?
Strangely when assigning a function with a wrong return type to doSomething
then Typescript will not complain. Why is that?
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?
}
};
在定义回调函数的类型然后传递返回错误"值的回调时会发生同样的事情:
Same thing happens when defining the type of a callback function and then pass a callback which returns a "wrong" value:
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/edit/typescript-callback-2
See example on stackblitz: https://stackblitz/edit/typescript-callback-2
推荐答案
你可以安全地使用一个回调,它的参数比定义的类型少,但不能不同或更多:
You can safely use a callback that has less parameters then the defined type, but not different or more:
test.doSomething(() => {...} // allowed
test.doSomething((user) => {...} // allowed
test.doSomething((user1, user2) => {...} // error
test.doSomething((username:string) => {...} // error
通过这种方式,您可以提供一个可能不需要调用它的所有值的回调.
This way you can provide a callback that probably doesn't need all values that it is called with.
然后您可以安全地向返回的对象添加更多属性,但您不能跳过必需的属性或更改它们的类型:
Then you can safely add more properties to the returned object, but you can't skip mandatory ones or change their types:
return { userName: 'test', bla: '123'} // ok, just an extra parameter
return { } // not ok, userName is required
return { userName: 42} // not ok, userName is required to be a string
没关系,因为结果的接收者可以忽略所有额外的属性,不会造成任何伤害.
It's ok because the receiver of the result can just ignore all extra properties, it causes no harm.
这篇关于打字稿函数/回调类型:使用“错误"分配函数时没有错误;返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论