let entities: {
clickPrice: number
} | undefined = Math.random() >= 0.5 ? {
clickPrice: Math.random()
} : undefined
const clickPrice = Math.random() >= 0.5 ? Math.random() : undefined
type testType = {
clickPrice: number
}
const test: {
clickPrice: number
}[] = []
if (entities || clickPrice) {
test.push({
clickPrice: entities ? entities.clickPrice : clickPrice
})
}
为什么会出现此错误:
Type 'number | undefined' is not assignable to type 'number'.
Type 'undefined' is not assignable to type 'number'.
在clickPrice
clickPrice: entities ? entities.clickPrice : clickPrice
?
我想要的是“如果有 entities
或 clickPrice
,请执行一些只能使用其中之一的代码”。
TS playground
答案 0 :(得分:2)
在类型缩小部分(特别是 "control flow analysis")中,您可以看到 TypeScript 如何处理类型。简而言之,TypeScript 可以缩小 entities
,也可以缩小 clickPrice
,但不能以对您有帮助的方式缩小表达式 entities || clickPrice
。
你必须打破它,以最小的可读性代价:
if (entities) {
test.push({clickPrice: entities.clickPrice});
} else if (clickPrice) {
test.push({clickPrice});
}
答案 1 :(得分:0)
因为您的类型明确将此属性定义为仅数字:
type testType = {
clickPrice: number
}
但是,您的代码指出,如果随机数 (0-1) 大于 0.5,则执行另一个随机数,否则返回 undefined:
const clickPrice = Math.random() >= 0.5 ? Math.random() : undefined
您需要更新类型以支持未定义或返回有效数字。
答案 2 :(得分:0)
您需要对 as as number
使用 clickPrice
,因为它可能未定义。
if (entities || clickPrice) {
test.push({
clickPrice: entities ? entities.clickPrice : clickPrice as number
})
}
Here 正在工作