react + typescript开发项目时ts报关于类型的错误

1,066 阅读1分钟

关于react + typescript开发项目时ts报一些类型的错误

     开发时经常遇到 Type ‘string | string[]‘ is not assignable to type ‘string | undefined‘的关于ts的类型报错:

Type 'string' is not assignable to type '"" | "warning" | "success" | "error" | "validating"'.ts(2322)

[FormItem.d.ts(19, 5): ]()The expected type comes from property 'validateStatus' which is declared here on type 'IntrinsicAttributes & FormItemProps<any>'

(JSX attribute) FormItemProps<Values = any>.validateStatus?: "" | "success" | "warning" | "error" | "validating"

     有时候即使变量类型正确也会报此错误,目前查得一种解决办法是使用typescript类型断言。有两种使用方式:
     <类型>值     或者     值 as 类型
     类型断言不会影响你为其设置的多种类型,因为它不是类型转换而是类型选择。推荐使用as形式,因为jsx这种语法中只支持as方式。举例:

//使用antd table的可选择表格时使用rowSelection的type属性时报错
   rowSelection: {
       type: 'checkbox'
   }
//使用类型断言后编译通过
  rowSelection: {
      type: 'checkbox' as 'checkbox'
  }