![](/img/trans.png)
[英]Why can't Typescript infer function argument types for optional arguments?
[英]why typescript can not infer types correctly
type A2 = {
label: 'name';
render: (v: string) => any;
} | {
label: 'age';
render: (v: number) => any;
} | {
label: ['name'];
render: (v: string) => any;
} | {
label: ['age'];
render: (v: number) => any;
}
const a1: A2 = {
label: 'age',
render: (v) => v,
}
const a2: A2 = {
label: ['name'],
render: (v) => v,
}
在 a1 中,渲染的“v”被正確推斷為“數字”。但在 a2 中,它是“任何”。我想知道差異是什么以及為什么。 這是 Typescript 的錯誤嗎?
只需按照 Samuli Hakoniemi 在評論中的建議將其發布為答案,以方便未來的觀眾。
您需要在數組定義中使用聯合:
type A2 = {
label: 'name' | 'age';
render: (v: string | number) => unknown;
} | {
label: ['name' | 'age'];
render: (v: string | number) => unknown;
}
const a1: A2 = {
label: 'age',
render: (v) => v,
}
const a2: A2 = {
label: ['name'],
render: (v) => v,
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.