如何在Flow中实现TypeScript里的'as'类型断言功能?
在Flow中实现类似TypeScript的类型断言操作
嘿,刚好我对Flow的类型系统很熟悉,这就帮你解决这个问题!
在TypeScript里你用null as LoginInterface做类型断言,Flow里有对应的语法,而且实现起来很直接。下面是几种符合你需求的写法:
1. 直接使用Flow的类型断言语法
Flow里的类型断言是用(值: 类型)的形式,和TS的as语法作用一致,都是告诉类型检查器“这个值就是我指定的类型,不用再做默认检查了”。对应你的代码,写法如下:
// 先定义接口,Flow里支持interface语法 interface LoginInterface { username: string; password: string; } const MyObject = { // 用(null: LoginInterface)把null断言成LoginInterface类型 credentials: (null: LoginInterface), otherInfo: "I'm something not relevant to this question" };
2. 给整个对象添加类型注释(更规范的写法)
如果想让整个对象的类型更清晰,也可以先定义对象的类型,再用断言给初始值:
interface LoginInterface { username: string; password: string; } // 定义整个对象的类型 type MyAppObject = { credentials: LoginInterface, otherInfo: string }; const MyObject: MyAppObject = { credentials: (null: LoginInterface), otherInfo: "I'm something not relevant to this question" };
补充:如果允许credentials为null或LoginInterface
如果你后续希望这个属性可以是null或者符合LoginInterface的对象,其实不需要断言,直接把类型定义成联合类型即可:
interface LoginInterface { username: string; password: string; } const MyObject = { credentials: null, otherInfo: "I'm something not relevant to this question" }: { credentials: LoginInterface | null, otherInfo: string };
这种写法更符合Flow的类型安全原则,如果你只是暂时把初始值设为null,后续会赋值为符合接口的对象,第一种断言写法就完全对应你TypeScript里的操作啦。
内容的提问来源于stack exchange,提问作者Kirkify
相关产品推荐
相关产品推荐

