0

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.

0

2 Answers 2

3

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!

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

Comments

0

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');

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.