首页 > 解决方案 > 使用对象扩展时类型不兼容

问题描述

我在打字稿中遇到了一个奇怪的错误,我在互联网上找不到。

type IDialogTypeProps = 'info' | 'alert' | 'success' | 'warning';

  interface IDialogProps {
    text: string;
    type: IDialogTypeProps;
  }

  const obj = {type: 'warning'}

const dialog:IDialogProps = {
  text: 'string',
  ...obj,
}

打字稿通过警告

Types of property 'type' are incompatible.
Type 'string' is not assignable to type 'IDialogTypeProps'

但是,如果我将type: string直接放在对话框对象中,打字稿将在没有警告的情况下编译。我相信这是一个很容易解决的问题。

标签: typescriptecmascript-6

解决方案


问题是您的obj对象在没有明确类型的情况下被 Typescript 假定为:

const obj: {
  type: string;
}

您可以通过将字符串表示为来强制 TS 不自动将推断类型从 扩大'warning'到。将 的定义更改为:string'warning'constobj

const obj = { type: 'warning' as const }

推荐阅读