首页 > 解决方案 > 如何限制一个对象在 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",
}

标签: typescript

解决方案


您可以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,

    };
}

推荐阅读