打字稿函数/回调类型:使用“错误"分配函数时没有错误;返回值

编程入门 行业动态 更新时间:2024-10-26 20:32:19
本文介绍了打字稿函数/回调类型:使用“错误"分配函数时没有错误;返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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:关键词]

本文发布于:2023-04-29 09:54:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1187973.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   错误   回调   返回值   分配

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!