强制执行 Typescript 对象的索引成员的类型? [英] Enforcing the type of the indexed members of a Typescript object?

查看:31
本文介绍了强制执行 Typescript 对象的索引成员的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to store a mapping of string -> string in a Typescript object, and enforce that all of the keys map to strings. For example:

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

有没有办法让我强制要求值必须是字符串(或任何类型..)?

Is there a way for me to enforce that the values must be strings (or whatever type..)?

推荐答案

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

这篇关于强制执行 Typescript 对象的索引成员的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆