简体   繁体   English

Typescript object 键映射的模板文字

[英]Typescript template literal for object key mapping

I'm trying to create a generic type that would map the keys using template literals.我正在尝试创建一个通用类型,该类型将使用模板文字 map 键。 In general i just want all the keys listed in the generic type to be present in the output type, but modified slightly.一般来说,我只希望通用类型中列出的所有键都出现在 output 类型中,但稍作修改。 Something along the lines of:类似的东西:

type TFoobar = "foo" | "bar";

const foobar: TFlagDict<TFoobar> = {
    "foo_flag": true,
    "bar_flag": true
};

I have tried implementing it like so:我试过像这样实现它:

type TFlagDict<TProperties extends string> = {
    [key in TProperties]: {[k in `${key}_flag`]: boolean}
}[TProperties]

And while it does have a proper typing, it makes the properties optional (at least one is required, but there is nothing that enforces they are all present)虽然它确实有一个正确的类型,但它使属性成为可选的(至少一个是必需的,但没有任何东西强制它们都存在)

const foo: TFlagDict<TFoobar> = {
    "foo_flag": true
}; //valid, shouldnt be

const bar: TFlagDict<TFoobar> = {
    "bar_flag": true
}; //valid, shouldnt be

const foobar: TFlagDict<TFoobar> = {
    "foo_flag": true,
    "bar_flag": true
}; //valid

You were close:你很接近:

type TFoobar = "foo" | "bar";

const foobar: TFlagDict<TFoobar> = {
    "foo_flag": true,
    "bar_flag": true
};

type TFlagDict<TProperties extends string> = {
    [key in TProperties as `${key}_flag`]: boolean // key remapping
}

type O = TFlagDict<TFoobar>
const foo: TFlagDict<TFoobar> = {
    "foo_flag": true
}; //error

const bar: TFlagDict<TFoobar> = {
    "bar_flag": true
}; //error

const foobar2: TFlagDict<TFoobar> = {
    "foo_flag": true,
    "bar_flag": true
}; //valid

Playground操场

You are allowed to use as inside iterator.您可以使用as内部迭代器。 See docs for more context有关更多上下文,请参阅文档

You can use TFooBar instead of key to enforce such validation:您可以使用TFooBar而不是key来强制执行此类验证:

type TFlagDict<TProperties extends string> = {
    [key in TProperties]: {[k in `${TFoobar}_flag`]: boolean}
}[TProperties]

Playground 操场

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

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