我想在Typescript对象中存储string ->字符串的映射,并强制所有值映射到字符串。例如:

var stuff = {};
stuff["a"] = "foo";   // okay
stuff["b"] = "bar";   // okay
stuff["c"] = false;   // ERROR!  bool != string

是否有一种方法让我强制值必须是字符串(或任何类型..)?


当前回答

你可以传递一个名字给未知键,然后写你的类型:

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

现在你可以在你的类型检查中使用它:

let stuff: StuffBody = {};

但对于FlowType,不需要有名称:

type StuffBody = {
  [string]: string,
};

其他回答

你可以传递一个名字给未知键,然后写你的类型:

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

现在你可以在你的类型检查中使用它:

let stuff: StuffBody = {};

但对于FlowType,不需要有名称:

type StuffBody = {
  [string]: string,
};

基于@shabunc的答案,这将允许将键或值(或两者都是)强制为您想强制的任何值。

type IdentifierKeys = 'my.valid.key.1' | 'my.valid.key.2';
type IdentifierValues = 'my.valid.value.1' | 'my.valid.value.2';

let stuff = new Map<IdentifierKeys, IdentifierValues>();

也应该使用enum而不是类型定义。

实际上有一个内置的实用程序记录:

    const record: Record<string, string> = {};
    record['a'] = 'b';
    record[1] = 'c'; // leads to typescript error
    record['d'] = 1; // leads to typescript error

定义接口

interface Settings {
  lang: 'en' | 'da';
  welcome: boolean;
}

强制键为设置界面的特定键

private setSettings(key: keyof Settings, value: any) {
   // Update settings key
}
var stuff: { [key: string]: string; } = {};
stuff['a'] = ''; // ok
stuff['a'] = 4;  // error

// ... or, if you're using this a lot and don't want to type so much ...
interface StringMap { [key: string]: string; }
var stuff2: StringMap = { };
// same as above