首页 > 解决方案 > 在 Typescript 中约束对象的值类型

问题描述

在打字稿中,如何为可以具有任何键的普通旧 javascript 对象编写类型签名,但值始终是字符串。例如,{a:"foo"},{b:"bar"}都是有效值,但{a:[1,2,3]}不是{b:3}

我希望能够写出类似的东西

let foo : {*: string} = {a: "foo"}

目前,我正在使用any它来实现这一点,但这并不像我想要的那样精确。

标签: typescripttypes

解决方案


您可以使用索引签名来声明所有值都是字符串...

type Example = { [key: string]: string };

例子:

type Example = { [key: string]: string };

const a: Example = {
    "anything": "any string", // ok
    anotherkey: "a string", // ok
    thirdKey: 1 // Error
};

推荐阅读