【问题标题】:Using an object prop as a key for another object in TS使用对象道具作为 TS 中另一个对象的键
【发布时间】:2019-10-31 04:33:31
【问题描述】:

我正在尝试导出具有有效类型的对象并基于它创建类型。它按预期工作。这里的问题是 Option 接口不接受对象键作为键名,即使它们是字符串。

export const SortValues = {
  NEWER: 'NEWER',
  OLDER: 'OLDER',
  NAME_ASC: 'NAME_ASC',
  NAME_DESC: 'NAME_DESC',
}

interface Option<T = string> {
  key: T;
  value: string;
}

type SortValuesType = keyof typeof SortValues;

// type SortValuesType = 'NEWER' | 'OLDER' | 'NAME_ASC' | 'NAME_DESC'; // This also doesn't work.

export const options: Array<Option<SortValuesType>> = [
  { key: SortValues.NEWER, value: 'Mais novos' },
  { key: SortValues.OLDER, value: 'Mais antigos' },
  { key: SortValues.NAME_ASC, value: 'A - Z' },
  { key: SortValues.NAME_DESC, value: 'Z - A' },
];

我在 options 的 key prop 上收到错误 "Type 'string' is not assignable to type '"NEWER" | "OLDER" | "NAME_ASC" | "NAME_DESC"'."

此外,如果我将 SortValues 定义为枚举,它也可以工作,但是它会给我带来一些其他问题,所以我需要将它导出为对象。

这是一个sn-p https://codesandbox.io/s/fqide

【问题讨论】:

    标签: typescript types typescript-typings


    【解决方案1】:

    您需要使用as const 断言。即使在 const 定义中,属性值也会扩大,因此 NEWER 的类型将是 string 而不是字符串文字类型 'NEWER'as const 将指示编译器保留字符串文字类型

    export const SortValues = {
      NEWER: 'NEWER',
      OLDER: 'OLDER',
      NAME_ASC: 'NAME_ASC',
      NAME_DESC: 'NAME_DESC',
    } as const
    

    PLAY

    【讨论】:

    • 这正是我所需要的。谢谢。
    猜你喜欢
    • 2023-01-10
    • 2022-01-25
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 2023-01-08
    • 1970-01-01
    • 2012-06-01
    相关资源
    最近更新 更多