如果你希望在构造函数中的参数'props'不可能为'undefined',可以使用'strictNullChecks'配置来强制类型检查。'strictNullChecks'配置可以在'tsconfig.json'文件中设置为'true'。

在启用了'strictNullChecks'配置之后,你需要修改'constructor'的签名,将'props'参数标记为非空类型'Props',而不是可选类型'Props?'。这样就可以确保在构造函数中传递的参数不为'undefined'。

以下是修改后的代码示例:

class Element<Props extends IElementProps = IElementProps> {
  constructor(props: Props) {
    // 在此处可以确保props不为undefined
  }
}

请注意,如果你不使用非空断言符'!',在使用'props'时需要先进行类型检查,以确保它不为'undefined'。例如:

class Element<Props extends IElementProps = IElementProps> {
  constructor(props?: Props) {
    if (props) {
      // 在此处可以确保props不为undefined
    }
  }
}

使用'!'非空断言符可以告诉TypeScript编译器,你已经确保了变量不为'undefined',因此可以放心地使用它。这在某些情况下可能是合适的,但要小心使用,确保你在使用之前已经进行了适当的类型检查。

TypeScript 类中构造函数参数类型推断为 undefined 的问题解决

原文地址: https://www.cveoy.top/t/topic/pyQf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录