如题。如何使用 defaultProps 属性中的类型,避免类型推断错误,可选属性出现可能 undefined?
如题。如何使用 defaultProps 属性中的类型,避免类型推断错误,可选属性出现可能 undefined?
TypeScript
中除了 as 断言和 尖括号<SomeType>
断言之外,还有一个非空断言。
下面这个不是报可能为undefined嘛,当你自己确定不会为空的时候可以在onToggle后面加上一个感叹号,断言前面的变量的不为空。 当然也可以使用可选链语法,使程序更健壮,万一真的不存在onToggle的时候也不至于报错
// 36行源代码
this.props.onToggle(this.state.expanded, this.closeMethod)
// 使用非空断言
this.props.onToggle!(this.state.expanded, this.closeMethod)
// 可选链
this.props.onToggle?.(this.state.expanded, this.closeMethod)
希望能对你的问题有一定帮助
上下两者毫无关系
解决办法, IProps 里面的相应属性去掉 ?(表示非必须属性)