我认为 TypeScript
尝试阅读属性时会提示 length
什么可能是array
或 never
,然后,我需要使用类型谓词缩小类型范围。不是这种情况。为什么 ?我怎样才能更改类型以便 TypeScript 强制我检查我不是在处理空对象?
// strictNullChecks = true
type Empty = Record<string, never>;
type NonEmpty = {
documents: Array<number>;
};
function isEmpty(x: Empty | NonEmpty): x is Empty {
return !("documents" in x);
}
const count = (x: Empty | NonEmpty) => {
// TypeScript does not complain about reading `length` property of `never`
// if (isEmpty(x)) {
// return 0;
// }
return x.documents.length;
};
最佳答案
下面是一个逐步类型的销毁示例:
type Empty = Record<string, never>;
type NonEmpty = {
documents: Array<number>;
};
function isEmpty(x: Empty | NonEmpty): x is Empty {
return !("documents" in x);
}
const count = (x: Empty | NonEmpty) => {
type D0 = typeof x.documents
type D1 = (Empty | NonEmpty)[`documents`]
type D2 = Empty[`documents`] | NonEmpty[`documents`]
type D3 = never | NonEmpty[`documents`]
type D4 = NonEmpty[`documents`]
type D5 = Array<number>
return x.documents.length; // x.documents is number[], that's why no error here
};
以下是可能符合您需要的预期行为示例:
type EmptyExpected = Record<string, undefined>;
const countExpected = (x: EmptyExpected | NonEmpty) => {
type D0 = typeof x.documents
type D1 = (EmptyExpected | NonEmpty)[`documents`]
type D2 = EmptyExpected[`documents`] | NonEmpty[`documents`]
type D3 = undefined | NonEmpty[`documents`]
type D4 = undefined | number[]
return x.documents.length; // x.documents is number[] | undefined, that's why it is an error here
};
关于typescript - 为什么 TypeScript 在尝试从联合类型中读取 never 时不报错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72109470/