我在尝试正确键入我的函数之一时遇到问题。在下面的代码中,x
的类型是 any
,我想输入比这更好的类型。
interface Pet {
name: string;
}
const checkType = (x: any): x is Pet => {
return 'name' in x && typeof x.name === 'string';
}
我发现 unknown
或 object
最合适,但两者都给我一个错误
interface Pet {
name: string;
}
const checkType = (x: unknown): x is Pet => {
return 'name' in x && typeof x.name === 'string';
}
Object is of type 'unknown'
interface Pet {
name: string;
}
const checkType = (x: object): x is Pet => {
return 'name' in x && typeof x.name === 'string';
}
Property 'name' does not exist on type 'object'
所以我的问题是,如何在不转换为 any
的情况下正确键入 x
?
以下可能是一个解决方案,但我发现它太多且具体了:
playground
interface Pet {
name: string;
}
const checkType = (x: object): x is Pet => {
return 'name' in x && typeof (x as {
name: unknown,
}).name === 'string';
}
更多信息:
任何
可能导致问题的示例:
最佳答案
我建议通过以下两种方式之一解决此问题:
第一个是 Typescript 手册中的示例所采用的方法(我假设您从中获得了“Pet”:
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
}
但是,如果您在通用库上工作,这会失败,因为您不知道您的消费者会为您提供什么,并且扩展该联盟并不是进行重大更改的好理由。然后你可以采取策略 #2:
interface IPojo {
[key: string]: any,
}
const checkType = (x: IPojo): x is Pet => {
return 'name' in x && typeof (x as {
name: unknown,
}).name === 'string';
};
function foo(p: Pet) {
console.log(p.name);
}
const bar: IPojo = {}
const baz = 'name';
bar[baz] = 'hi';
foo(bar); // TypeError, compiler can't verify bar.name
if (checkType(bar)) {
foo(bar); // No TypeError, type narrowed correctly by your guard
}
Playground
关于typescript - 键入一个 "type predicate"没有任何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63796285/
相关文章:
amazon-web-services - 如何更改 CodePipeline 工件行为? (如果可
javascript - Three.JS - 使用相同的骨骼结构在 SkinnedMeshes 之
angular - Jasmine Angular : How to write unit test
node.js - Next.js - GetStaticPaths 类型错误
python-3.x - 由于使用 Docker 的 PostgresDB 连接失败,无法启动 Ap
java - Apache Storm 本地集群 "Unable to canonicalize a
scala - 如何解决 `/packages cannot be represented as U