联合类型的部分键作为打字稿中对象的键 [英] Partial keys of union type as key of an object in typescript

查看:26
本文介绍了联合类型的部分键作为打字稿中对象的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在打字稿中使用联合类型的键作为对象的键.

I want to use the keys of the union type as key of the object in typescript.

type EnumType = 'a1' | 'a2'

const object:{[key in EnumType]: string}= {
 a1: 'test'
}

在这种情况下,我甚至必须添加 a2 作为对象中的键.有没有办法让它成为可选的?

In this case I have to add even a2 as a key in the object. Is there a way to make this optional?

推荐答案

只需像这样添加一个问号:

Just add a question mark like this:

type EnumType = 'a1' | 'a2'

const object:{[key in EnumType]?: string}= {
 a1: 'test'
}

object 定义与您当前的代码:

The object definition with your current code:

const object: {
    a1: string | undefined;
    a2: string | undefined;
}

变成:

const object: {
    a1?: string | undefined;
    a2?: string | undefined;
}

允许每个键都是可选的.

Allowing every key to be optional.

这篇关于联合类型的部分键作为打字稿中对象的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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