根据文档,“TypeScript 中的类型兼容性基于结构子类型”。所以这是可能的:
type Person: {
name: string;
}
const developer = {
name: 'Joe',
language: 'Typescript',
}
// this is ok because Person is a subtype of typeof developer
const otherDeveloper: Person = developer; // who writes code like that?!
这有很多后果,其中之一是在使用 Object.keys 时会丢失类型信息:
// "keys" type is array of strings not `name` literal as this would be of course wrong because in runtime "keys" is ['name', 'language']
const keys = Object.keys(otherDeveloper);
因此,我试图按照他们的承诺在 TS 文档中找到这种子类型的原因,但我找不到
仔细考虑了 TypeScript 允许不合理行为的地方,在整个文档中,我们将解释这些情况发生的地方以及它们背后的激励场景。
这可能对我有帮助的唯一地方是一个需要更窄类型对象的函数,例如:
function getName(person: Person) {
return person.name;
}
getName(developer); // works fine because of subtyping
如果您在这种情况下必须使用强制转换,我个人认为这不是什么大问题:
getName(developer as Person);
还有其他我可能遗漏的例子吗?