以下代码导致错误:
example/not-following.ts:15:1 - error TS2722: Cannot invoke an object which is possibly 'undefined'. 15 run(true).maybe(); ~~~~~~~~~~~~~~~
代码:
interface Something { maybe?: () => void; } function run(isTrue: boolean): Something { const object: Something = {}; if (isTrue) { object.maybe = (): void => { console.log('maybe'); }; } return object; } run(true).maybe();
任何解决此问题的聪明方法?我很惊讶TypeScript没有遵循此规则。
以下代码导致错误:example / not-following.ts:15:1-错误TS2722:无法调用可能为'undefined'的对象。 15运行(true).maybe(); ~~~~~~~~~~~~~~~~代码:...
无法调用可能是'undefined'的对象。
我想TypeScript很聪明,但可能不那么聪明,以至于它完全验证了这类运行时执行路径。