TypeScript中的函数

4

为什么没有缺失错误?

interface User {
  // way 1
  foo(): string;  
  foo2(x:number): string; 

  // way 2
  normal: () => string;
  normal2: (x:number) => string;
}

let user: User = {
  // way 1
  foo: () => '',
  foo2: () => '', // why no error since x is missing
  
  // way 2
  normal: () => '',
  normal2: () => '', // why no error since x is missing
};

See this Typescript Playground


我尝试在 user 上调用那些函数,按预期收到了错误 - 不确定为什么在它们的定义中没有错误。 - Jack Bashford
@AmadouBeye 不行。必须有一些变量可以具有未定义的值。值不能停留在空气中,而必须仅在变量中以供参考。 - umesh kadam
3个回答

3
一个低函数可以分配给一个高阶函数,只要它的返回类型是兼容的,并且存在的参数是兼容的。
在您的情况下,因为函数没有参数并返回一个string,它们是兼容的。 TS Playground
type NumFn = (n: number) => string;
declare const isCompatible: (() => string) extends NumFn ? true : false; // true

奇怪,为什么还会出现这样的行为?我们如何断言来阻止这种行为呢? - umesh kadam
1
@umeshkadam 为什么你想这样做?遇到了什么问题吗? - jsejcksn
没什么大不了的,只是在学习。如果能更精确一些就更好了。 - umesh kadam

3
如果您调用不传参的 (x:number)=>string,您会收到 An argument for 'x' was not provided. 错误信息。 但这并不是您正在做的事情 您正在将 ()=>string 赋值给 (x:number)=>string,这是有效的。当您将 ()=>string 赋值给 (x:number)=>string 时,编译器会问:能否使 ()=>string 的行为与 (x:number)=>string 相同?
也就是说,()=>string 是否可以接受一个 number,然后输出一个 string,就像 (x:number)=>string 所做的那样?
答案是肯定的,()=>string 技术上可以接受任何数字,但只是忽略它,然后返回一个字符串,独立于接收的数字是什么。因此,()=>string 可以分配给 (x:number)=>string

0

就像上面的答案一样,似乎只有在调用没有参数的函数时才能检测到它。 我猜这与 TypeScript 的上下文类型有关 (我也在学习)

函数参数逐个进行检查,每个对应参数位置的类型相互检查。如果您不想完全指定类型,则 TypeScript 的上下文类型可以推断出参数类型,因为函数值直接分配给类型为 SearchFunc 的变量。同样,我们的函数表达式的返回类型也由它返回的值隐含确定 typescript handbook

interface Counter {
  (start: number): string;
  interval: number;
  foo: (x:number) => string;
  bar(x:number):string;
  reset(): void;
}

function getCounter(): Counter {
  let counter = function (s...

游乐场链接


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接