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

Inferring type of function parameters from usage #16916

Closed
yahiko00 opened this issue Jul 3, 2017 · 3 comments
Closed

Inferring type of function parameters from usage #16916

yahiko00 opened this issue Jul 3, 2017 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@yahiko00
Copy link

yahiko00 commented Jul 3, 2017

When dealing with large JavaScript codebases, it would be convenient if TypeScript could infer the type of function parameters from their usage in the body.

As a short example:

function inferenceParam(param) {
    let x = param * 3; // param is inferred to be a number as well as x
    ...
    let str = "Value of param : " + param; // Here param is implicitly casted to a string
    console.log(param.wrongProperty); // Error since param is a number and no wrongProperty exists on Number.
}

TypeScript inferred x is a number. I am just wondering if this could be possible the type inference could backtrack the type of param, also as a number?

@yahiko00 yahiko00 changed the title Infering type of function parameters from usage Inferring type of function parameters from usage Jul 3, 2017
@Jessidhia
Copy link

Jessidhia commented Jul 4, 2017

x is inferred as a number because, no matter what the operand is, the result will be a number (or an exception).

const x = ({ toString () { return '42' } }) * 3
console.log(typeof x, x) // "number", 126

TypeScript does not infer the type of function parameters, unless they come from a function expression's context.

@mhegazy
Copy link
Contributor

mhegazy commented Aug 28, 2017

Please see #15196

@mhegazy mhegazy added the Duplicate An existing issue was already created label Aug 28, 2017
@mhegazy
Copy link
Contributor

mhegazy commented Sep 12, 2017

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

@mhegazy mhegazy closed this as completed Sep 12, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants