2

Consider the following function.

public static convert<T, U>(t: T, conversion: ((toutput: T) => U) = ((t) => t)) { 
    return conversion(t);
}

Typescript currently complains about the toutput parameter return from the conversion function, which is the defaulted parameter:

Type 'T' is not assignable to type 'U'. 'U' could be instantiated with an arbitrary type which could be unrelated to 'T'.

I'm attempting to get the IDE to recognize that, given the default parameter, T is the same as U.

My use cases are the following:

convert(1) // returns 1
convert(1, x => ({x})) // returns an object with { x : 1 }

Is there any way that anybody knows of to silence the compiler and be able to create this function above properly?

2 Answers 2

1

I think you could accomplish this with overloads:

public static function convert<T>(t: T): T;
public static function convert<T, U>(t: T, conversion: (t: T) => U): U;
public static function convert<T, U>(t: T, conversion?: (t: T) => U) {
    return conversion ? conversion(t) : t;
}

..

const foo = convert(1)             // inferred type 1
const bar = convert(1, x => ({x})) // inferred type { x : number }

The 1 gets widened to number because implicit literal types are widened in the context of return values (e.g. x => ({x})), which in turn causes the T to inferred as number. You can avoid this by explicitly typing the first parameter:

const bar = convert(1 as 1, x => ({x})) // inferred type { x: 1 }
Sign up to request clarification or add additional context in comments.

Comments

1

Try it like this:

static convert<T, U = T>(t: T, conversion: ((toutput: T) => U) = t => t as T & U) {
  return conversion(t);
}

const x = convert(1);
const y = convert(1, x => ({x}));

Use T as default value for U, and cast the return type of default value of conversion function as T & U.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.