【问题标题】:Building a prefixer type using typescripts Template literal type feature使用打字稿模板文字类型功能构建前缀类型
【发布时间】:2021-03-24 09:56:30
【问题描述】:

我想使用字面量类型功能为接口中的所有键添加前缀,但我对类型的理解太有限了。

到目前为止,我得到的是以下内容:

export type Prefix<K extends string, T extends string> = `${K}${T}`;

export type Prefixer<K, T extends string> = {
    [Prefix<P in keyof K>]: K[P];
};

用法如下:

interface Animals {
   fish: any;
}

type SuperAnimals = Prefixer<Animals, 'super'>;

有人可以帮忙吗?

【问题讨论】:

标签: typescript types typescript-generics


【解决方案1】:

TS4.1 announcement/ TS4.1 beta 以来,此语法似乎发生了变化。

工作地点

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-1.html#key-remapping-in-mapped-types

看来我们可以:

export type Prefix<K extends string, T extends string> = `${K}${T}`;

export type Prefixer<K, T extends string> = {
    [P in keyof K as Prefix<T, string & P>]: K[P];
};


interface Animals {
    fish: any;
}

type SuperAnimals = Prefixer<Animals, 'super'>;

Playground link

为了获得更多乐趣,您可以将Prefix 定义为

export type Prefix<K extends string, T extends string> = `${K}${Capitalize<T>}`;

产生像 superFish 这样的道具,而不是 superfish

【讨论】:

    猜你喜欢
    • 2019-04-10
    • 1970-01-01
    • 2022-01-11
    • 2019-09-07
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    • 2021-11-26
    • 2018-12-13
    相关资源
    最近更新 更多