React with Typescript 中作为状态的两个字符串之一

One of two strings as state in React with Typescript

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

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
}

问题是这引发了 linting 错误:

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" 是模式允许的类型之一?

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

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

根据 typedefs 定义如下:

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,它甚至会在代码提示中包含正确的值。