使用打字稿模板文字类型功能构建前缀类型 [英] Building a prefixer type using typescripts Template literal type feature

查看:31
本文介绍了使用打字稿模板文字类型功能构建前缀类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to prefix all keys in an interface using the literal type feature, but my understanding of types is too limited.

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

What I got so far is the following:

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'>;

有人可以帮忙吗?

推荐答案

TS4.1 公告/TS4.1 beta.

The syntax for this appears to have changed since the 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'>;

游乐场链接

为了更有趣,您可以将 Prefix 定义为

For extra fun you can define Prefix as

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

导致像 superFish 这样的道具而不是 superfish.

resulting in props like superFish instead of superfish.

这篇关于使用打字稿模板文字类型功能构建前缀类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆