首页 > 解决方案 > 强制 TypeScript 推断常量值而不是字符串

问题描述

有没有办法强制 TypeScript 将类型推断为传递给函数的特定值,而不是一般类型?

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

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

我知道我可以通过写作来获得想要的类型,infer<'one' | 'two'>('one', 'two')但我不想重复自己。

标签: typescript

解决方案


您可以使用可变元组类型

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

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

或者只提供适当的约束:

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

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

如果你想了解更多关于函数参数的推理,你可以查看我的文章 我描述了关于推理的最流行的问题


推荐阅读