Krz*_*ski 5 typescript template-literals
我正在尝试创建一个通用类型,该类型将使用模板文字映射键。一般来说,我只希望泛型类型中列出的所有键都出现在输出类型中,但稍作修改。大致如下:
type TFoobar = "foo" | "bar";
const foobar: TFlagDict<TFoobar> = {
"foo_flag": true,
"bar_flag": true
};
Run Code Online (Sandbox Code Playgroud)
我尝试像这样实现它:
type TFlagDict<TProperties extends string> = {
[key in TProperties]: {[k in `${key}_flag`]: boolean}
}[TProperties]
Run Code Online (Sandbox Code Playgroud)
虽然它确实有正确的类型,但它使属性成为可选的(至少有一个是必需的,但没有任何东西强制它们全部存在)
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
Run Code Online (Sandbox Code Playgroud)
你很接近:
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
Run Code Online (Sandbox Code Playgroud)
您可以使用as内部迭代器。有关更多上下文,请参阅文档
| 归档时间: |
|
| 查看次数: |
2166 次 |
| 最近记录: |