打字稿对象:如何将键限制为特定字符串? [英] Typescript object: How do I restrict the keys to specific strings?

查看:81
本文介绍了打字稿对象:如何将键限制为特定字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个 Partial 类型的对象,其中的键将是'a','b'或'c'的某种组合.它不会具有所有3个键(但是至少会有一个).如何在Typescript中强制执行此操作?这是更多详细信息:

I want to create an object of type Partial, where the keys will be some combination of 'a', 'b', or 'c'. It will not have all 3 keys (edit: but it will at least have one). How do I enforce this in Typescript? Here's more details:

// I have this:
type Keys = 'a' | 'b' | 'c'

// What i want to compile:
let partial: Partial = {'a': true}
let anotherPartial: Partial = {'b': true, 'c': false}

// This requires every key:
type Partial = {
  [key in Keys]: boolean;
}

// This throws Typescript errors, says keys must be strings:
interface Partial = {
  [key: Keys]: boolean;
}

我上面尝试过的两种方法(使用映射的类型和接口)无法实现我想要的.有人可以帮忙吗?

The two methods I've tried above (using mapped types and interfaces) don't achieve what I want. Can anyone help here?

推荐答案

您可以使用?将键设置为可选,所以

You can use the ? to make the keys optional, so

interface Partial {
   a?: boolean;
   b?: boolean;
   c?: boolean;
}

或者,您可以执行以下操作:

Or, you can do this:

type Keys = "a" | "b" | "c";

type Test = {
    [K in Keys]?: boolean
}

这篇关于打字稿对象:如何将键限制为特定字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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