typescript - 如何限制一个对象在 Typescript 中只具有字符串值?
问题描述
我需要创建一个只有字符串作为其值的对象。所以我需要将日期对象转换为字符串(ISO 8601 格式)。我在一个类中做了一个这样的方法
toPayloadData() : Map<string, string> {
// all the payload data that need to be sent via FCM should be in string
return {
body: this.body,
createdAt: this.createdAt.toISOString(), // convert Date to ISO 8601 string format
creatorID: this.creatorID,
creatorImageURL: this.creatorImageURL,
creatorName: this.creatorName,
title: this.title,
};
}
如您所见,我: Map<string, string>
在上面使用,以便在输入不是字符串的值时给出错误。
但我有这样的错误:
Type '{ body: string; createdAt: string; creatorID: string; creatorImageURL: string; creatorName: string; title: string; }'
is not assignable to type 'Map<string, string>'.
Object literal may only specify known properties, and 'body' does not exist in type 'Map<string, string>'.
在 Kotlin、Swift 和 Dart 中,我可以这样限制它,但我猜 Typescript 中的对象和 Map 是不同的
那么我上面的方法的返回类型是什么所以我只能返回一个具有字符串值的对象
return {
key1: "string in here",
key2: "string in here",
}
解决方案
您可以Record<string, string>
用作可读的内置类型。
这是这样的构造类型的简写:{ [key: string]: string }
. 意思是一个带有字符串类型键的对象,每个对象都有一个字符串类型的值。
toPayloadData() : Record<string, string> {
return {
body: this.body,
createdAt: this.createdAt.toISOString(), // convert Date to ISO 8601 string format
creatorID: this.creatorID,
creatorImageURL: this.creatorImageURL,
creatorName: this.creatorName,
title: this.title,
};
}
推荐阅读
- c++ - fscanf 返回无意义的值
- node.js - 无法为节点构建本机包
- localhost - data-item-url 位于 localhost 而不是 pythonanywhere (wagtail + snipcart 项目)
- go - Golang 泛型 - 简单用例
- python - WindowsError:[错误 998] 在 python 中使用 ctypes 时
- gif - 如何为 .GIF 文件压缩 LZW 编码的图像数据?
- machine-learning - one-hot 编码是否会导致特征不平衡的问题?
- javascript - 使用基于选定的一个 ActionResult 从不同表中获取结果
- r - 如何在 r 中更改树形图的颜色
- python-3.x - 使用 Subprocess 来避免长时间运行的任务断开 discord.py bot?