模板字面量类型

与js语法相同,但只能在类型操作中使用。多用于基于一个类型内部的信息定义一个新的字符串

当模板中的变量是一个联合类型时,每一个可能的字符串字面量都会被表示

如果模板字面量里的多个变量都是联合类型,结果会交叉相乘

1
2
3
4
5
6
7
8
9
10
11
type EmailLocaleIDs = "welcome_email" | "email_heading";
type FooterLocaleIDs = "footer_title" | "footer_sendoff";

type AllLocaleIDs = `${EmailLocaleIDs | FooterLocaleIDs}_id`;
// type AllLocaleIDs = "welcome_email_id" | "email_heading_id" | "footer_title_id" | "footer_sendoff_id"

type AllLocaleIDs = `${EmailLocaleIDs | FooterLocaleIDs}_id`;
type Lang = "en" | "ja" | "pt";

type LocaleMessageIDs = `${Lang}_${AllLocaleIDs}`;
// type LocaleMessageIDs = "en_welcome_email_id" | "en_email_heading_id" | "en_footer_title_id" | "en_footer_sendoff_id" | "ja_welcome_email_id" | "ja_email_heading_id" | "ja_footer_title_id" | "ja_footer_sendoff_id" | "pt_welcome_email_id" | "pt_email_heading_id" | "pt_footer_title_id" | "pt_footer_sendoff_id"

类型中的字符串联合类型

1
2
3
4
5
6
7
8
type PropEventSource<Type> = {
on(eventName: `${string & keyof Type}Changed`, callback: (newValue: any) => void): void;
};

/// Create a "watched object" with an 'on' method
/// so that you can watch for changes to properties.

declare function makeWatchedObject<Type>(obj: Type): Type & PropEventSource<Type>;

string & keyof Type 不能写成 keyof Type,会报错。因为keyof返回的是 string|number|symbol 类型,而模板字面量要求的类型是 string | number | bigint | boolean | null | undefined 多了一个symbol类型。可以通过Exclude或Extract去除symbol或提取string避免上述错误

内置字符操作类型

  • Uppercase
    把每个字符转为大写形式
  • Lowercase
    把每个字符转为小写形式
  • Capitalize
    把字符串的第一个字符转为大写形式
  • Uncapitalize
    把字符串的第一个字符转换为小写形式
作者

徐云飞

发布于

2022-10-27

更新于

2023-02-05

许可协议

评论