“考虑改用映射对象类型."- 什么是映射对象类型以及如何在此处使用它? [英] "Consider using a mapped object type instead." - what's a mapped object type and how do I use it here?

查看:52
本文介绍了“考虑改用映射对象类型."- 什么是映射对象类型以及如何在此处使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

interface Foo { 
    [foo: "hello" | "world"]: string;
}

我收到类似的错误消息

An index signature parameter type cannot be a union type. Consider using a mapped object type instead.

什么是映射对象类型,我该如何使用它?

What is a mapped object type, and how do I use it?

推荐答案

映射的对象类型对一组单例类型进行操作,并生成一个新的对象类型,其中每个单例都变成了一个属性名称.

A mapped object type operates on a set of singleton types and produces a new object type where each of those singletons is turned into a property name.

例如:

type Foo = {
    [K in "hello" | "world"]: string
};

相当于

type Foo = {
    "hello": string;
    "world": string;
};

请记住,映射的对象类型是一个不同的类型运算符 - 大括号中的语法不能用于接口或具有其他成员的对象类型.例如

Keep in mind that a mapped object type is a distinct type operator - that syntax in the braces can't be used in interfaces, or object types with other members. For example

interface Foo {
    [K in "hello" | "world"]: string
}

产生以下错误:

A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type.

映射对象类型可用于许多不同的事情.在此处阅读更多信息:http://www.typescriptlang.org/docs/handbook/advanced-types.html#mapped-types

Mapped object types are useful for a lot of different things. Read more here: http://www.typescriptlang.org/docs/handbook/advanced-types.html#mapped-types

这篇关于“考虑改用映射对象类型."- 什么是映射对象类型以及如何在此处使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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