React with Typescript

时间:2018-10-30 14:03:47

标签: reactjs typescript typescript-typings react-tsx typescript-types

我有一个看起来像这样的组件:

export interface Props {
  // ... some props
}

export interface State {
  readonly mode: "add" | "delete"
}

export class MyComponent extends Component<Props, State> {
  readonly state = { mode: "add" }
  // ... more component code
}

问题在于这会引发掉毛错误:

Property 'state' in type 'ScannerScreen' is not assignable to the same property in base type 'Component<Props, State, any>'.
  Type '{ mode: string; }' is not assignable to type 'Readonly<State>'.
    Types of property 'mode' are incompatible.
      Type 'string' is not assignable to type '"add" | "delete"'.

为什么TypeScript无法识别"add""delete"是字符串还是"add"是模式允许的类型之一?

2 个答案:

答案 0 :(得分:1)

这是由于类型推断引起的-TypeScript将'add'推断为string,而不是类型'add'。您可以执行以下操作轻松解决此问题:mode: "add" as "add"。您还可以为状态使用类型注释:readonly state: State = { mode: "add" }

答案 1 :(得分:0)

state已在基本组件中定义(如错误所述)。

根据typedef定义如下:

state: Readonly<S>;

尝试

export interface Props {
  // ... some props
}

export interface State {
  readonly mode: "add" | "delete"
}

export class MyComponent extends Component<Props, State> {
  // VSCode will have intellisense for this ...
  this.state = { mode: "add" };
  // ... more component code
}

如果您使用的是VSCode,则代码提示中甚至还会包含正确的值。