Skip to content

function overloads with string literal and other params no errors report. #31582

@XGHeaven

Description

@XGHeaven

Search Terms

Function, String Literal

Suggestion

Show code:

interface T {
  (name: 'a', options: { key1: string }): string
  (name: 'b', options: { key2: string }): string
  (name: string, options?: any): string
}

const t: T = name => name

t('a') 
// ^^^^ no error occurs

I know why there is no error. Typescript try to match the first overload. But no match. Then try to match second overload. Also not. But matched in the last overload. So there is no errors occur.

But I suggest typescript to throw error. I want function invoked with 'a' must have the second param {key1: string}, and invoked with 'b' must have the second param {key2: string}. The other string without any limited.

Use Cases

I write a i18n function to generate string. In some key, the second param cannot be ignored. And others is no limited.

function intl(key: 'X', value: {key: string}): string
function intl(key: string, value: any): string

intl('X') // error
intl('X', {key: 'aaa'}) // correct

Examples

In above.

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions