TypeScript 类构造函数参数类型推断与非空断言
在 TypeScript 中,默认情况下,函数参数是可选的,即可以传递 undefined 或者不传递该参数。如果你希望参数 "props" 是必需的,你可以在构造函数中使用非空断言操作符 "!" 来告诉 TypeScript 不允许传递 undefined。
以下是一个示例:
class Element<Props extends IElementProps = IElementProps> {
constructor(props?: Props) {
// 使用非空断言操作符来确保 props 不为 undefined
this.props = props!;
}
private props: Props;
}
现在,当你创建 "Element" 类的实例时,如果不传递 "props" 参数,TypeScript 将会报错,提示你需要传递参数。
const element = new Element(); // 错误,需要传递参数
const elementWithProps = new Element({ prop1: 'value1' }); // 正确
通过使用非空断言操作符 "!",你告诉 TypeScript 在构造函数中 "props" 参数是必需的,并且不可以为 undefined。这样做会带来一些风险,因为如果在创建实例时没有传递 "props" 参数,那么在构造函数中访问 "props" 属性时会导致运行时错误。
原文地址: https://www.cveoy.top/t/topic/pyP9 著作权归作者所有。请勿转载和采集!