microsoft / TypeScript-Website

The Website and web infrastructure for learning TypeScript
https://www.typescriptlang.org
Creative Commons Attribution 4.0 International
2.23k stars 1.37k forks source link

CRITICAL: example error in functions chapter, writing-good-overloads section #3048

Open simply-none opened 7 months ago

simply-none commented 7 months ago

Page URL: https://www.typescriptlang.org/docs/handbook/2/functions.html#writing-good-overloads

Issue:

the example is error:

Because both overloads have the same argument count and same return type, we can instead write a non-overloaded version of the function:

function len(x: any[] | string) {
  return x.length;
}

above has some problems in typescript playground:

No overload matches this call.
  Overload 1 of 2, '(s: string): number', gave the following error.
    Argument of type 'number[] | "hello"' is not assignable to parameter of type 'string'.
      Type 'number[]' is not assignable to type 'string'.
  Overload 2 of 2, '(arr: any[]): number', gave the following error.
    Argument of type 'number[] | "hello"' is not assignable to parameter of type 'any[]'.
      Type 'string' is not assignable to type 'any[]'.

correct is that:

function len(x: any[] | string): number;
nyngwang commented 7 months ago

Where is the error?

image
simply-none commented 7 months ago

Where is the error?错误在哪里?

image

look: image by the document context,the example is error.

nyngwang commented 7 months ago

Oh, I got your point. But in this case, I think they mean this: (By the word "instead", they're replacing all overloaded signatures with the union type any[] | string)

Because both overloads have the same argument count and same return type, we can instead write a non-overloaded version of the function:

image
simply-none commented 7 months ago

Oh, I got your point. But in this case, I think they mean this: (By the word "instead", they're replacing all overloaded signatures with the union type any[] | string)哦,我明白你的意思了。但在这种情况下,我认为他们的意思是:(通过“代替”这个词,他们正在用联合类型 any[] | string 替换所有重载的签名)

Because both overloads have the same argument count and same return type, we can instead write a non-overloaded version of the function:由于两个重载具有相同的参数计数和相同的返回类型,因此我们可以改为编写函数的非重载版本:

image

oh, i get it. thank you!