Kousha
Kousha

Reputation: 36299

Typescript variable generics

I know this is possibly doesn't exist, but can Typescript have a variable number of generics, each of their own type?

For example, instead of having something like function name(...args: any[]), I'd like to have a way that you could so something like

function name<T1, T2, T3...>(arg1: T1, arg2: T2, ...)

So if I were to do

name('string', 123, true)

I can then have the types of string, number, boolean as my generic types in the method.

Upvotes: 0

Views: 85

Answers (2)

Krantisinh
Krantisinh

Reputation: 1729

It definitely is possible I guess. In below example, we should have type inference at every step while invoking the function getProperty.

function getProperty<T, K extends keyof T>(obj: T, key: K) {
    return obj[key];
}

export interface User {
    name: string;
}

type k = keyof User;

const user = { name: 'Krantisinh' };

getProperty<User, k>(user, 'name');

Upvotes: 0

jcalz
jcalz

Reputation: 330466

Full-blown variadic kinds are not implemented in TypeScript, but luckily for your particular use case you can use tuple types in rest/spread expressions introduced in TS3.0:

function nameFunc<T extends any[]>(...args: T) {};

nameFunc('string', 123, true); // T inferred as *tuple* [string, number, boolean]

And you can access the individual member types via numeric lookup types:

// notice that the return type is T[1]
function secondItem<T extends any[]>(...args: T): T[1] {
  return args[1];
}
const num = secondItem("string", 123, true); // number

Hope that helps; good luck!

Upvotes: 3

Related Questions