Home > Enterprise >  How to make a declared function automatically infer types based on usage?
How to make a declared function automatically infer types based on usage?

Time:12-08

I feel like this should totally be possible in typescript, but it seems as if typescript doesn't properly type this. Is there any way to do this? Here's a super simple example, but I'm specifically looking to automatically infer argument types when passing a function to a react component's prop that takes a callback with a defined type

Actual

function constrainingFunction(b: number) {
    return b   1
}

function test(a) { // ERROR: `a` implicitly has an `any` type
    constrainingFunction(a)
}

test(1)

Expected

function constrainingFunction(b: number) {
    return b   1
}

function test(a) { // `a` should properly be inferred as `number`
    constrainingFunction(a)
}

test(1)

CodePudding user response:

See animated screenshot

So that might be some consolation for you.

Playground link to code

CodePudding user response:

  1. Type inference is a convenience. It makes sense for local variables. It does not make sense for function signatures. You would be gaining a minor local convenience at the expense of global type safety. Local variables have limited scope, and inference won't break things far away. It would undermine the point of static type checking.

  2. Type inference happens based on assignments to the variable. Not what a variable is assigned to -- In other words, the type of the left hand side of an assignment is inferred, not the right hand side.

    You're looking at it backwards. If inference worked the way you're thinking, a lot of things would break.

I don't do React, but maybe what you should be looking at is Generic Types, which can infer types based on how they are used.

  • Related