gpt4 book ai didi

typescript - 为什么当参数的形状与 typescript 中的参数形状不同时它不会抛出错误?

转载 作者:行者123 更新时间:2023-12-01 23:10:41 25 4
gpt4 key购买 nike

代码如下:

function a(fn: (a: string) => void) {
fn("Hello, World");
}
a(function b() {
return 1
});

通过将类型注释添加到函数a 的回调中,这意味着函数a 必须接收一个函数,该函数具有string 类型的参数> 和 void 类型的返回值。但是当我传递了不满足类型注解条件的函数b时,TS还是没有抛出编译错误。为什么?

此外,当我将传递给 fn 的值从 "Hello, world"(string) 更改为 123(number),它确实抛出了一个错误。在这种情况下,类型注释起作用了。

最佳答案

这里有两件事:

Why are functions with fewer parameters assignable to functions that take more parameters?

Why are functions returning non-void assignable to function returning void?

上面的两个链接来自 Typescript 常见问题解答,它应该可以让您清楚地了解上述行为。归根结底,这是以下两个合乎逻辑的结论的预期结果:

  1. 应允许您作为回调传递的函数不使用字符串类型的参数 a
  2. 在预期为 none 时返回更多信息,即 void,没问题。

所以,这是行不通的,因为函数 b 需要一个数字,而 a 会传递一个字符串。

// Argument of type '(p: number) => number' is not assignable to parameter of type '(a: string) => void'.
// Types of parameters 'p' and 'a' are incompatible.
// Type 'string' is not assignable to type 'number
a(function b(p: number) {
return 1
});

但是这会起作用,因为 b 没有使用函数 a 将传递给它的字符串......它应该没问题。

a(function b() {
return 1
});

这是 TS Playground 的链接:https://tsplay.dev/WyObJN

function a(fn: (a: string) => void) {
fn("Hello, World");
}


a(function b() {
return 1
});


// Argument of type '(p: number) => number' is not assignable to parameter of type '(a: string) => void'.
// Types of parameters 'p' and 'a' are incompatible.
// Type 'string' is not assignable to type 'number
a(function b(p: number) {
return 1
});


function a1(fn: (a: string) => number) {
fn("Hello, World");
}

// Argument of type '(p: string) => string' is not assignable to parameter of type '(a: string) => number'.
// Type 'string' is not assignable to type 'number'.(2345)
a1(function b(p: string) {
return p;
});

因此,只有当传递的回调与回调参数兼容时,回调函数中的形状不匹配才会起作用。

关于typescript - 为什么当参数的形状与 typescript 中的参数形状不同时它不会抛出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69989397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com