语法上没啥问题,但是,符合语法只能保证编译通过,不能保证运行不出错啊
这样啊,我还以为运行也不会报错的
可上面那个打印不会报错,直接报的undefined,是因为undefined没有firstName所以报错的嘛
原文出自哪里?
@qianyu0710: ts是强类型的,在编译时需要类型检查,any的作用是跳过类型检查,上文给出的只是个示例演示,其实际用处是在有些对象还不明确推测出类型时,编译时跳过类型检查,使其在运行时可以通过。目前的示例只是个示例,并不是实际使用时的具体案例。
上面链接对其进行了阐述:
In some situations, not all type information is available or its declaration would take an inappropriate amount of effort. These may occur for values from code that has been written without TypeScript or a 3rd party library. In these cases, we might want to opt-out of type checking. To do so, we label these values with the any type:
myName本身就是undefined你还想访问firstName,建议anyThing.myName?.firstName
只有这楼是正解,这是js基础,和ts关系不大