为了账号安全,请及时绑定邮箱和手机立即绑定

萌新求教!Typescript为什么要区别对待对象字面量和对象引用?感激不尽

萌新求教!Typescript为什么要区别对待对象字面量和对象引用?感激不尽

鸿蒙传说 2019-08-11 14:10:13
Typescript为什么要区别对待对象字面量和对象引用?interfaceProps{a:number}letobjAB={a:1,b:2}letdemo1:Props={a:1,b:2//Error}letdemo2:Props=objAB//Ok
查看完整描述

2 回答

?
潇湘沐

TA贡献1816条经验 获得超6个赞

However,TypeScripttakesthestancethatthere’sprobablyabuginthiscode.Objectliteralsgetspecialtreatmentandundergoexcesspropertycheckingwhenassigningthemtoothervariables,orpassingthemasarguments.Ifanobjectliteralhasanypropertiesthatthe“targettype”doesn’thave,you’llgetanerror:Source
应该是ts认为letdemo2:Props=objAB是把objAB当作Props使用,但是letdemo1:Props={a:1,b:2}则是直接实现了一个接口,所以需要严格进行校验吧。所以这样letdemo1:Props={a:1,b:2}asProps;是可以的。
                            
查看完整回答
反对 回复 2019-08-11
  • 2 回答
  • 0 关注
  • 327 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号