英文:
Defined a function which asserts object fields are non-nullable but not work, how to fix it?
问题
我在TypeScript中定义了一个函数,像这样:
export function assertsNotNil
obj: T
): asserts obj is {
[P in keyof T]-?: NonNullable<T[P]>;
} {
const nilFields = Object.entries(obj)
.filter(([key, value]) => isNil(value))
.map(([key]) => key);
if (nilFields.length) {
throw new Error(对象的某些字段为空:${nilFields.join(',')}
);
}
}
我想要使用它来断言一些类型实际上是非空的,这样我就不需要以后再次检查:
const data: string | null = 1 + 1 === 2 ? "abc" : null;
assertsNotNil({ data });
console.log(data.toUpperCase())
但它并没有像我期望的那样工作:
[![在这里输入图片描述][1]][1]
哪里出了问题,我应该如何修复它?
[1]: https://i.stack.imgur.com/7uo6m.png
英文:
I defined a function in TypeScript like this:
export function assertsNotNil<T extends object>(
obj: T
): asserts obj is {
[P in keyof T]-?: NonNullable<T[P]>;
} {
const nilFields = Object.entries(obj)
.filter(([key, value]) => isNil(value))
.map(([key]) => key);
if (nilFields.length) {
throw new Error(`Some fields of the object are nil: ${nilFields.join(',')}`);
}
}
I want to use it to assert some types are actually non-nullable so I don't need to check again later:
const data: string | null = 1+1 === 2 ? "abc": null;
assertsNotNil({data});
console.log(data.toUpperCase())
But it doesn't work as I expected:
Where is wrong and how should I fix it?
答案1
得分: 1
已经通过你的断言检查的事实是,当数据成员通过传递到类型断言函数的对象访问时,编译器会知道:
const data: string | null = 1 + 1 === 2 ? "abc" : null;
const obj = { data };
assertsNotNil(obj);
console.log(data.toUpperCase()); // 错误,'data' 可能为 'null'
console.log(obj.data.toUpperCase()); // 正确
const { data: dataAlias } = obj;
console.log(dataAlias.toUpperCase()); // 正确
英文:
Facts checked by your assertion are known to the compiler when data members are accessed via object passed into the type assertion function:
const data: string | null = 1+1 === 2 ? "abc": null;
const obj = {data};
assertsNotNil(obj);
console.log(data.toUpperCase()); // ERROR, 'data' is possibly 'null'
console.log(obj.data.toUpperCase()); // OK
const {data: dataAlias} = obj;
console.log(dataAlias.toUpperCase()); // OK
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论