javascript - typescript 对象 : How do I restrict the keys to specific strings?

标签 javascript string typescript object key

我想创建一个 Partial 类型的对象,其中的键是“a”、“b”或“c”的某种组合。它不会拥有所有 3 个键(编辑:但它至少会有一个)。我如何在 Typescript 中执行此操作?以下是更多详细信息:

// 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;
}

我在上面尝试过的两种方法(使用映射类型和接口(interface))没有达到我想要的效果。有人可以帮忙吗?

最佳答案

您可以使用 ? 使键成为可选的,所以

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

或者,您可以这样做:

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

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

关于javascript - typescript 对象 : How do I restrict the keys to specific strings?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47251559/

相关文章:

javascript - 在 React 应用程序中切换到 TypeScript 的问题

javascript - 如何实现 float 可拖动面板

javascript - 删除右边的所有兄弟而不是左边的JQUERY JAVASCRIPT

javascript - 根据状态和索引动态更改样式组件

javascript - 如何将现有回调 API 转换为 Promise?

regex - 在R中按最后一个空格分割字符串

python - 如何将列表元素转换为列表?

c - 如果字符串还包含字母,如何将 char 字符串转换为一个 int 数字

ios - Ionic 4 IOS Socket.io如何动态获取配置

typescript - 异常 : No Directive annotation found on AgGridNg2