Rico Kahler
Rico Kahler

Reputation: 19202

Why does typescript not capture my type in this generic function?

The type isn't captured when using generics inside of a configuration object in some cases.

In particular, the function functionAThatTakesAnObject should capture the type of aNumber so that the type of shouldBeInferedToBeANumber should be number but instead it's given type {}

Any ideas why? What am I missing here? Is this a bug?

Here is a typescript playground link.

And here is the code:

function functionA<T>(funcThatReturnsT: (something: any) => T, funcThatTakeT: (t: T) => any) {
    let something = undefined as any;
    let hasTypeT = funcThatReturnsT(something);
    return funcThatTakeT(hasTypeT);
}

let aNumber = 5;

// works
functionA(() => aNumber, shouldBeInferedToBeANumber => shouldBeInferedToBeANumber.toExponential());
// still works
functionA(_ => aNumber, shouldBeInferedToBeANumber => shouldBeInferedToBeANumber.toExponential());

/**
 * this is the same as `functionA` but it takes a configuraton object instead
 */
function functionAThatTakesAnObject<T>(opts: {
    funcThatReturnsT: (something: any) => T,
    funcThatTakeT: (t: T) => any
}) {
    let something = undefined as any;
    let hasTypeT = opts.funcThatReturnsT(something);
    return opts.funcThatTakeT(hasTypeT);
}

// works
functionAThatTakesAnObject({
    funcThatReturnsT: () => aNumber, // if there is no parameter, it works
    funcThatTakeT: shouldBeInferedToBeANumber => shouldBeInferedToBeANumber.toExponential()
});

// DOES NOT WORK
functionAThatTakesAnObject({
    funcThatReturnsT: _ => aNumber, // if there is a parameter, it breaks
    funcThatTakeT: shouldBeInferedToBeANumber => shouldBeInferedToBeANumber.toExponential()
});

Edit:

clarification from my comment:

I'm asking why the type isn't being inferred. I don't want to explicitly say the type. for some background, I'm writing a javascript library in typescript and the javascript users can't add that assertion so the only way the typings will work for them is if the type is inferred through usage.

Upvotes: 1

Views: 152

Answers (1)

Alejandro Lora
Alejandro Lora

Reputation: 7802

Fixed, just mark the type like this: enter image description here

EDITED:

This is another way: enter image description here

EDITED 2: (made it compatible with JS)

enter image description here

Upvotes: 1

Related Questions