2

I have a problem which boils down to trying to assign a function with a specific parameter type to a variable expecting a function with a generic type:

const s: <T>(v: T)=>string 
  = (v: string[])=>(v[0]||'x');

Playground version.

Typescript gives the following error:

Type '(v: string[]) => string' is not assignable to type '(v: T) => string'. Types of parameters 'v' and 'v' are incompatible. Type 'T' is not assignable to type 'string[]'.

This error doesn't make much sense to me, as it seems like string[] is a perfectly reasonable type to use for the generic T.

There is a related question that has the same underlying problem, but the answer there was specific to circumstances in that question: Why is this TypeScript class implementing the interface not assignable to a generic constraint extending the interface?

2
  • 1
    <T>(v: T) => string means the type of a function which can consume anything and output a string; your function can only consume an array of strings. Commented Jan 14, 2021 at 5:30
  • const s: <T extends string[]>(v: T) => string = (v: string[]) => (v[0] || 'x'); Commented Jan 14, 2021 at 7:19

2 Answers 2

1

As mentioned by kaya3, you are trying to assign a function that take a specific type, string[], to a function that takes generic types . What you may do instead, is, define a type with the generic signature. And then create a function that takes is one specific instance of that generic signature. Something like this:

type MyType<T> = (v: T) => string;
const s: MyType<string[]>  = (v: string[]) => v[0] || 'x' ;

If you have just one type, this would be sufficient:

const s  = (v: string[]) => v[0] || 'x' ;
Sign up to request clarification or add additional context in comments.

1 Comment

That was my answer too, but I was six seconds late
0

You are trying to take a function that takes an array of strings and returns a string, and assign that function to a variable that takes any T and returns a string. A function that takes an array of strings as input cannot take any T as input.

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.