Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
simply-none opened this issue Mar 26, 2024 · 4 comments

Comments

@simply-none
Copy link

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
Copy link

Where is the error?

image

@simply-none
Copy link
Author

Where is the error?错误在哪里?

image

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

@nyngwang
Copy link

nyngwang commented Apr 11, 2024

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
Copy link
Author

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants