Home > Back-end >  Force TypeScript to infer constant values instead of string
Force TypeScript to infer constant values instead of string

Time:11-17

Is there a way to force TypeScript to infer type as specific values passed into function, not a general type?

function infer<T>(...args: T[]): T[] {
   return args;
}

const numbers = infer('one', 'two'); // Inferred type of numbers: string[]
                                     // Desired type of numbers: ('one' | 'two')[]

I know I can achieve desired type by writing infer<'one' | 'two'>('one', 'two') but I'd like to not repeat myself.

CodePudding user response:

You can use variadic tuple types:

function infer<T extends string, A extends T[]>(...args: [...A]) {
   return args;
}

const numbers = infer('one', 'two'); // ["one", "two"]

OR just provide appropriate constraint:

function infer<T extends string>(...args:T[]) {
   return args;
}

const numbers = infer('one', 'two'); // ("one" | "two")[]

If you want to lear more about inference on functionarguments you can check my article I have described most popular questions about inference

  • Related