TypeScript 中关联对象数组的接口 [英] Interface for associative object array in TypeScript

查看:38
本文介绍了TypeScript 中关联对象数组的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的对象:

var obj = {
    key1: "apple",
    key2: true,
    key3: 123,
    .
    .
    .
    key{n}: ...
}

所以 obj 可以包含任意数量的命名键,但值必须都是字符串、布尔值或数字.

So obj can contain any number of named keys, but the values must all be either string, bool, or number.

如何在 TypeScript 中将 obj 的类型声明为接口?我可以声明联合类型或类似类型的关联数组(或可变参数元组)吗?

How do I declare the type of obj as an interface in TypeScript? Can I declare an associative array (or variadic tuple) of a union type or something similar?

推荐答案

是的,您可以使用 索引签名:

interface MyType {
    [key: string]: string | boolean | number;
}

var obj: MyType = {
    key1: "apple",
    key2: true,
    key3: 123
};

这篇关于TypeScript 中关联对象数组的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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