我知道并理解unknown in TypeScript所做的事情。我有一个不可信的输入,输入为unknown。我想检查一下它在input.things.0下是否有真实的价值。
function isFullOfGreatThings(input: unknown) {
return Boolean(input?.things?.[0]);
}TypeScript抱怨Object is of type 'unknown' -但是我知道类型是未知的,这就是为什么我要测试键下的值。
如何在TypeScript?中测试未知对象中的密钥
发布于 2022-06-22 17:30:00
这取决于您想要的安全程度,以及作为类型检查安全过程的一部分需要多少运行时代码。
如果您真正关心的是一个布尔结果,那么您只需将input转换为any并使用您拥有的,包装在一个在catch块中返回false的try...catch中:
function isFullOfGreatThings (input: unknown): boolean {
try {
return Boolean((input as any)?.things?.[0]);
}
catch {
return false;
}
}从TS游乐场编译的JS:
"use strict";
function isFullOfGreatThings(input) {
try {
return Boolean(input?.things?.[0]);
}
catch {
return false;
}
}
const inputs = [
{ get things() { throw new Error('Oops'); } },
{ things: { get 0() { throw new Error(`It's a trap`); } } },
'hello',
2,
false,
true,
null,
['a', 'b', 'c'],
{ a: 1 },
{ things: ['something special'] },
{ things: 'text' },
{ things: { nested: 'things' } },
Symbol('snowflake'),
BigInt(0),
];
for (const input of inputs) {
console.log(input, isFullOfGreatThings(input));
}
https://stackoverflow.com/questions/72719320
复制相似问题