Skip to content

Infer overload signatures from implementation bodies #10765

Closed
@tekacs

Description

@tekacs

TypeScript Version: nightly (2.1.0-dev.20160906)

Code

function f(s: 'a'): string
function f(s: 'b'): number
function f(s: string): string | number {
    switch (s) {
        case 'a':
            return 'a';
        case 'b':
            return '2';
        default:
            return s;
    }
}

function g(x: string): number;
function g(x: number): string;
function g(x: string | number): string | number {
    if (typeof x === 'string') {
      return 'also a string';
    } else {
      return x.toString();
    }
}

// Math.sqrt(f('a')) // => Error
Math.sqrt(f('b')) //=> Compiles, to Math.sqrt(f('b')) == Math.sqrt('2')

Expected behavior: fails typechecking f(s: 'b') is annotated as returning a number, but returns a string in the implementation.

Actual behavior: typechecks successfully

I understand that the lattermost function in each case should typecheck as an isolated unit, only I would have hoped that this could be checked or at least warned about.

Given that we can throw an error in the below example, I think it should be possible to typecheck the above examples:

function h(x: string | number | boolean): number {
  if (typeof x === 'number') {
    return x;
  } else {
    return parseInt(x); // Error: Argument of type 'string | boolean' is not assignable to parameter of type 'string'.
  }
}

Edit: tsconfig.json is { "compilerOptions": { "strictNullChecks": true, "noImplicitAny": true } }

Metadata

Metadata

Assignees

No one assigned

    Labels

    DeclinedThe issue was declined as something which matches the TypeScript visionSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions