type DateFormat = {
year: "numeric";
}
function calculateDate (dateFormat: DateFormat) {
/**
*
*/
}
const format = {
year: "numeric"
}
calculateDate(format)
目前在 Typescript 4.2 中,format
的推断类型定义是:
{
year: string;
}
这与函数调用 (DateFormat
) 中的预期类型别名 calculateDate
不匹配,因为 string
类型的 year 属性不像字符串文字 numeric
。
但是,如果我直接从函数调用中传递了 format
对象参数,TS 似乎能够推断出调用上下文中的类型 - 并根据 DateFormat 正确验证类型。
calculateDate({
year: "numeric"
})
因此,我想知道这是 Typescript 推理算法能力的限制,还是语言的主动设计决策?
答案 0 :(得分:0)
您必须使用 const assertion as const
:
const format = {
year: "numeric"
} as const;
引自文档:
<块引用>当我们用 const 断言构造新的文字表达式时,我们 可以向语言发出信号
回答评论中的问题:
是的,这是一个设计决定,因为宽型和紧型都有用例。
我们想要拥有宽类型的一个例子是:
function foo(opts = {
color: 'blue'
}) {}
foo({
color: 'green'
})
在这种情况下,我们希望 color
属性的类型为 string
- 而不是 blue
。
答案 1 :(得分:0)
这个算法叫做Excess Property Checks
<块引用>对象文字在将它们分配给其他变量或将它们作为参数传递时会得到特殊处理并进行额外的属性检查。如果对象字面量具有“目标类型”没有的任何属性,您将收到错误: