它跟JS是相同的语法,但它只能用在类型操作中

  1. type World = "world"
  2. type Greeting = `hello ${World}`
  3. type EmailLocaleIDs = "welcome_email" | "email_heading";
  4. type FooterLocaleIDs = "footer_title" | "footer_sendoff";
  5. type AllLocaleIDs = `${EmailLocaleIDs | FooterLocaleIDs}_id`;
  6. type AllLocaleIDs = `${EmailLocaleIDs | FooterLocaleIDs}_id`;
  7. type Lang = "en" | "ja" | "pt";
  8. type LocaleMessageIDs = `${Lang}_${AllLocaleIDs}`;
  9. // 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. type PropEventSource<Type> = {
  2. on(eventName: `${string & keyof Type}Changed`,
  3. callback: (newValue: any) => void): void;
  4. };
  5. declare function makeWatchedObject<Type>(obj: Type): Type & PropEventSource<Type>;
模板字面量推断
  1. type PropEventSource<Type> = {
  2. on<Key extends string & keyof Type>
  3. (eventName: `${Key}Changed`, callback: (newValue: Type[Key]) => void ): void;
  4. };
  5. 声明一个函数签名 返回结果 T 以及PropEventSource 并集结果 所以结果是有 on属性的
  6. on属性是一个 Tkeyof得到的属性,它具有一个参数 是模板字符串 Key+Changed
  7. declare function makeWatchedObject<Type>(obj: Type): Type & PropEventSource<Type>;
  8. const person = makeWatchedObject({
  9. firstName: "Saoirse",
  10. lastName: "Ronan",
  11. age: 26
  12. });
  13. person.on("firstNameChanged", newName => {
  14. // (parameter) newName: string
  15. console.log(`new name is ${newName.toUpperCase()}`);
  16. });
内置字符串操作符
  1. type Greeting = "Hello, world"
  2. type ShoutyGreeting = Uppercase<Greeting>
  3. // type ShoutyGreeting = "HELLO, WORLD"
  4. type ASCIICacheKey<Str extends string> = `ID-${Uppercase<Str>}`
  5. type MainID = ASCIICacheKey<"my_app">
  6. // type MainID = "ID-MY_APP"
  7. type Greeting = "Hello, world"
  8. type QuietGreeting = Lowercase<Greeting>
  9. // type QuietGreeting = "hello, world"
  10. type ASCIICacheKey<Str extends string> = `id-${Lowercase<Str>}`
  11. type MainID = ASCIICacheKey<"MY_APP">
  12. // type MainID = "id-my_app"
  13. type LowercaseGreeting = "hello, world";
  14. type Greeting = Capitalize<LowercaseGreeting>;
  15. // type Greeting = "Hello, world"
  16. type UppercaseGreeting = "HELLO WORLD";
  17. type UncomfortableGreeting = Uncapitalize<UppercaseGreeting>;
  18. // type UncomfortableGreeting = "hELLO WORLD"