首页 > 解决方案 > 打字稿将对象文字视为合同接口/类型

问题描述

我正在编写一个创建对象文字的测试。例如:

const myObject = {
  id: 1,
  name: 'egg',
  error: null
}

的初始化值为myObject.error空。但是,当我稍后尝试将其设置为新值时。例如:

myObject.error = ['exception', 'mapping']

我为其分配了一个新值,string[]但出现错误:

Type 'string[]' is not assignable to type 'null'.ts(2322)

myObject 不是接口或类型,那么为什么它期望它始终为空值?

谢谢!

标签: javascripttypescript

解决方案


发生这种情况是因为您没有专门为myObjectconst 定义任何其他类型,这将导致 TypeScript 默认分配以下类型定义:

const myObject: {
    id: number;
    name: string;
    error: null;
}

是的,null它是 TypeScript 类型,显然string[]与它不兼容。但是,您可以自己定义类型,并使其兼容,如下所示:

type ObjectType = {
    id: number;
    name: string;
    error: null | string[];
}

const myObject: ObjectType = {
  id: 1,
  name: 'egg',
  error: null
}

myObject.error = ['exception', 'mapping']

这样一来,您就可以让 TypeScript 知道,它myObject.error可以采用nullstring[]type 值。


推荐阅读