LCB
LCB

Reputation: 1050

Getting error message while using Generic in typescript

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

Upvotes: 1

Views: 172

Answers (1)

Aleksey L.
Aleksey L.

Reputation: 38006

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

Upvotes: 2

Related Questions