【问题标题】:Use object values as interface keys使用对象值作为界面键
【发布时间】:2021-02-11 18:18:12
【问题描述】:

我有一个包含以下形式的属性名称的对象:

const INPUT_NAMES = {
    FIRST_NAME: 'first-name',
    LAST_NAME: 'last-name'
};

我想根据这些属性名称值生成一个接口:

interface IPropertyFormat {
    [INPUT_NAMES.FIRST_NAME]: string;
    [INPUT_NAMES.LAST_NAME]: string;
}

这不起作用,因为我没有使用文字类型,也没有使用符号,我得到了这个:A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type.

使用一个简单的常量,例如:

const KEY = "FIRST_NAME";

interface IPropertyFormat {
    [KEY]: string;
}

有效,但在我的情况下不是一个优雅的解决方案,如果可能的话,我想避免它。我已经查看了this other kinda related topic,但它没有为我的问题提供解决方案。

有人知道如何解决这个问题吗?

编辑:

此外,再次使用 const 断言找到了一个“有点什么”解决方案 at this post

【问题讨论】:

  • @Nishant 我什至不确定这与我的问题有什么关系。
  • @zhulien 也许我理解错了,但这能解决你的问题吗? tsplay.dev/rw2DYm在重复问题中是一样的
  • @Nishant 是的,这更像它。谢谢你。就像我提到的,const assertion 很有帮助,我不知道这个功能。

标签: typescript


【解决方案1】:

要在INPUT_NAMES 中拥有正确的文字类型,您应该使用as const

Link to playground

const INPUT_NAMES = {
    FIRST_NAME: 'first-name' as const,
    LAST_NAME: 'last-name' as const
};

type Result =  {
    [k in typeof INPUT_NAMES[keyof typeof INPUT_NAMES]]: string
}

type Expected = {
    'first-name': string,
    'last-name': string
}

declare const x: Expected
declare const y: Result
// In case Result and Expected are different types, there will be an error
const a: Expected = y
const b: Result = x

如果有一个接口很重要:

interface myInterface extends Result {}

【讨论】:

  • 感谢您提供包含接口的扩展解决方案。由于我的属性有不同的类型,我仍然需要手动构建接口,分别指定每种类型,但现在我有办法让它更干。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-13
  • 2021-07-27
  • 2013-12-17
  • 2011-10-21
  • 2022-01-05
  • 2022-01-25
相关资源
最近更新 更多