0

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

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

4

2 回答 2

1

这是由于类型推断——TypeScript 将推断'add'asstring而不是 type 'add'。您可以通过以下方式轻松解决此问题mode: "add" as "add":您还可以对状态使用类型注释:readonly state: State = { mode: "add" }

于 2018-10-30T14:15:01.253 回答
0

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

于 2018-10-30T14:40:34.980 回答