gpt4 book ai didi

typescript - 可选的链接运算符奇怪的行为

转载 作者:行者123 更新时间:2023-12-05 09:28:21 24 4
gpt4 key购买 nike

我在 TypeScript (v4.6.2) 中遇到了一些奇怪的行为。为什么 (a) 有效而 (b) 和 (c) 无效?

const a: string[] | null = []
if (a?.length > 1) {
console.log(1)
}

const b = [] as (string[] | null)
if (b?.length > 1) {
console.log(1)
}

const c: string[] | null = [] as (string[] | null)
if (c?.length > 1) {
console.log(1)
}

enter image description here

TypeScript playground

最佳答案

考虑以下几点:

TS Playground

const a: string[] | null = []
a // string[]
// TS has narrowed this to the array type in the union
// because you assigned an array to the variable after the type annotation

if (a?.length > 1) { // ok
console.log(1)
}

const b = [] as (string[] | null)
b // string[] | null
// You asserted that the array could be null,
// so it is now possibly null in the type system

if (b?.length > 1) {
// ~~~~~~~~~
// Object is possibly 'undefined'.(2532)
// TS won't allow comparison of a number to undefined
console.log(1)
}

const c: string[] | null = [] as (string[] | null)
c // string[] | null
// Another case of assertion

if (c?.length > 1) {
// ~~~~~~~~~
// Object is possibly 'undefined'.(2532)
// TS won't allow comparison of a number to undefined
console.log(1)
}

// I suggest one of these patterns instead:
declare const maybeNullMaybeArray: string[] | null;

if ((maybeNullMaybeArray?.length ?? 0) > 1) {
// ^^^^
// Use nullish coalescing operator to evaluate the expression to 0
// in the case that it is nullish, so that the comparison will
// always be between two numbers

maybeNullMaybeArray // string[] | null
// but the type is still not narrowed, because the true condition
// could have resulted from the evaluation to the literal zero
// instead of a value from the `length` property on the variable
// so, alternatively:
}

if (maybeNullMaybeArray && (maybeNullMaybeArray.length > 1)) {
// ^^^^^^^^^^^^^^^^^^^^^^^^^^
// The array definitely exists at this point
// so if we got this far, we can use it as an array:

maybeNullMaybeArray // string[]
}

参见:

关于typescript - 可选的链接运算符奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71391850/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com