1

I got error messages with the code below in the playground of typescript.

enter image description here

function fn<T, M = T[]>( x: T ): M {
    return [ x ];
}

How can I fix this and am I using the Generic in a wrong way?

I am so sorry about the simple code, and the real situation I encountered is like this:

type M<T> = { [key: string]: T };


function create<T>(names: string[], value: T): M<T> {
    return names.reduce((a: M<T>, c: string): M<T> => (a[c] = value, a), {} );
}

I want to change the code to:

function create<T, M = { [key: string]: T }>(names: string[], value: T): M {
    return names.reduce((a: M, c: string): M => (a[c] = value, a), {} );
}

Playground Link

2
  • Why do you need the second type parameter? Just function fn<T>( x: T ) { return [ x ]; } Commented Jun 7, 2020 at 8:33
  • The real code is more complex, I just made a simple example and ran it in the playground. Commented Jun 7, 2020 at 8:36

1 Answer 1

2

You don't really need the second type parameter:

function create<T>(names: string[], value: T): Record<string, T> {
    return names.reduce((a, c) => (a[c] = value, a), {} as Record<string, T>);
}

** Record<string, T> is just an alias to { [key: string]: T }

Playground

Sign up to request clarification or add additional context in comments.

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.