typescript - 强制 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')
但我不想重复自己。
解决方案
您可以使用可变元组类型:
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")[]
如果你想了解更多关于函数参数的推理,你可以查看我的文章 我描述了关于推理的最流行的问题
推荐阅读
- api - 富文本的最佳实践。休息。后端
- flutter - 使用 LineMetrics 获取文本高度的颤振问题
- conv-neural-network - 图像的位深度会影响卷积神经网络吗?
- qt - QtQuick QML如何在悬停时突出显示ListView中的项目?
- flask - EventSource 每 3 秒不断断开连接并重试连接
- javascript - 流添加永远不会被 agora.io 触发
- c# - 如何在 asp.net mvc 中获取子模式集合时包含基本模型属性
- regex - 匹配任何不是 az 或 AZ 或 & 后跟数字的内容
- linux - 替代“树”命令或减少树输出文件大小的方法?
- dart - 我是否具有由我正在实现的接口继承的实现方法和变量?