Reputation: 1050
I got error messages with the code below in the playground of typescript.
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), {} );
}
Upvotes: 1
Views: 172
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 }
Upvotes: 2