我的应用程序收到“消息”。我首先验证未知输入以确保它遵循预期的消息格式:
const isMessage = x =>
typeof x === 'object' &&
x !== null &&
typeof x['data'] === 'string';
我希望在 TypeScript 中输入此内容。这是我所拥有的:
type Message = { data: string };
const isMessage = (x: unknown): x is Message =>
typeof x === 'object' &&
x !== null &&
typeof x['data'] === 'string';
但是,这无法进行类型检查,因为:
Element implicitly has an 'any' type because expression of type '"data"' can't be used to index type '{}'.
Property 'data' does not exist on type '{}'.
类型保护之后typeof x === 'object' && x !== null
, TypeScript 给出输入x : object
。这似乎与x : {}
。但这种类型不允许我检查对象的任何属性。
代替x: object
,我想我想要一个“字典”类型,例如x: { [key: string | number | symbol]: unknown }
。但这不是 TypeScript 从类型保护中给我的输入typeof x === 'object'
.
我可以用as
铸造x
到字典类型:
const isMessage = (x: unknown): x is Message =>
typeof x === 'object' &&
x !== null &&
typeof (x as { [key: string | number | symbol]: unknown })['data'] === 'string';
这种类型检查,但它真的又长又笨拙,而且我不确定as
类型转换确实是类型安全的。
我读到了关于in算子缩小,基于此,我预计添加'data' in x
会工作:
const isMessage = (x: unknown): x is Message =>
typeof x === 'object' &&
x !== null &&
'data' in x &&
typeof x['data'] === 'string';
然而,这没有什么区别; TypeScript 仍然抱怨我无法索引x
,即使在某个点'data' in x
。为什么会这样in
运算符不允许我索引x
?