javascript - 打字稿将对象文字视为合同接口/类型
问题描述
我正在编写一个创建对象文字的测试。例如:
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 不是接口或类型,那么为什么它期望它始终为空值?
谢谢!
解决方案
发生这种情况是因为您没有专门为myObject
const 定义任何其他类型,这将导致 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
可以采用null
或string[]
type 值。
推荐阅读
- command-line - 使用设备树时将内核参数从 U-Boot 传递到 ARM Linux
- python - 允许用户直接下载文件 django
- wordpress - 需要在革命滑块中用新 URL 替换旧 URL
- python - 如何简化使用变量?
- android - 如何在数据绑定中使用 kotlin.Int?
- keycloak - 由于 KC 通过其他模式表解析,keycloak 启动需要很长时间
- ms-access - 请帮助我了解访问查询
- mysql - HEAP:删除重复名称并在单个条目中添加值
- scala - 创建 Spark 会话时出现 ClassNotFoundException
- ocaml - 如何使用 ocamlc 选项 -dprofile 和 -dtimings?