简体   繁体   English

使用 object 值作为接口键

[英]Use object values as interface keys

I have an object containing property names in the form:我有一个包含以下形式的属性名称的 object:

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

I want to generate an interface based on those property name values:我想根据这些属性名称值生成一个接口:

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

That doesn't work because I am not using a literal type, nor a symbol and I get this: A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type.这不起作用,因为我没有使用文字类型,也没有使用符号,我得到了这个: A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type.

Using a simple constant like:使用一个简单的常量,如:

const KEY = "FIRST_NAME";

interface IPropertyFormat {
    [KEY]: string;
}

works but is not an elegant solution in my case and would like to avoid it if possible.有效,但在我的情况下不是一个优雅的解决方案,如果可能的话,我想避免它。 I've checked out this other kinda related topic but it doesn't provide a solution for my problem.我已经检查了这个其他有点相关的主题,但它没有为我的问题提供解决方案。

Anyone has any idea how to work around this problem?任何人都知道如何解决这个问题?

EDIT:编辑:

Also, found a "some-what" solution at this post once again using const assertions .此外,在这篇文章中再次使用const assertions找到了一个“有点什么”的解决方案。

To have the correct litteral types in INPUT_NAMES you should use as const要在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

If having an interface is very important:如果有一个接口很重要:

interface myInterface extends Result {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM