美文网首页
模板字面量类型

模板字面量类型

作者: sweetBoy_9126 | 来源:发表于2022-07-30 10:29 被阅读0次

作用:减少 ts 重复代码

type CssPadding = "padding-left" | "padding-right" | "padding-top" | "padding-bottom"

type MarginPadding = "margin-left" | "margin-right" | "margin-top" | "margin-bottom"

上面两个 type 里面的 left right top bottom 都是重复代码

简化

type Direction = 'left | 'right' | 'top' | 'bottom'

type CssPadding = `padding-${Direction}`
type MarginPadding = `margin-${Direction}`

语法

`${T}`T 是类型变量可以是 string number boolean bigint

传入基本类型

type EvenName<T extends string> = `${T}Changed`
type Concat<S1 extends string, S2 extends string> = `${S1}-${S2}`

type T0 = EvenName<'foo'> // 'fooChanged'
type T1 = Concat<'hello', 'world'> // 'hello-world'

传入联合类型

type T3 = EvenName<'foo' | 'bar' | 'baz'> 
// 'fooChanged' | 'barChanged' | 'bazChanged'

type T4 = Concat<'top' | 'bottom', 'left' | 'right'>
// 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'

对于模板字面量类型来说如果传入的类型占位符的实际类型是联合类型
1). 单个占位符的联合类型自动展开

`[${T}]` 如果 T 是 A | B | C
那么就会变成 `[${A}]` | `[${B}]` | `[${C}]`

2). 多个占位符的联合类型解析为交叉

// S1 => A | B  S2 => C | D
`${S1}-${S2}`
结果为 `${A}-${C}` | `${A}-${D}` | `${B}-${C}` | `${B}-${D}`

相关文章

  • 模板字面量类型

    作用:减少 ts 重复代码 上面两个 type 里面的 left right top bottom 都是重复代码 ...

  • ES6系列 (三)模板字面量

    特性 模板字面量实现字符串插值 模板字面量实现多行字符串 模板字面量实现可重用的模板 理解标记模板字面量如何自定义...

  • 字面量

    字面量 常见字面量的默认类型 可以通过typealias修改字面量的默认类型 swift自带类型之所以能够通过字面...

  • TypeScript基础入门之高级类型的字符串字面量类型

    转发 TypeScript基础入门之高级类型的字符串字面量类型 高级类型 字符串字面量类型 字符串字面量类型允许你...

  • golang类型字面量

    类型字面量又被称作“未命名类型” 基本上除自定义类型、预定义类型外都是类型字面量。 以下都是类型字面量: gola...

  • TypeScript—字面量类型

    为什么会有字面量类型 先来做个小小的测试题,你能准确猜出来,下面 TS 代码中变量的类型吗? 等待十秒中…… 答案...

  • JavaScript基础 面向对象

    包装对象 原始类型(字面量\值类型)boolean number str字面量创建过程 只有原始类型才有包装对象...

  • TypeScript——高级类型(3)

    数字字面量类型 TypeScript还具有数字字面量类型。 function rollDie(): 1 | 2 |...

  • [Swift5.1] 22-字面量

    字面量 上面代码中的10、false、"Jack"就是字面量 常见字面量的默认类型 Swift自带的绝大部分类型,...

  • Swift5.0 - day9-字面量协议、模式匹配

    一、字面量 1.1、常见字面量的默认类型public typealias IntegerLiteralType =...

网友评论

      本文标题:模板字面量类型

      本文链接:https://www.haomeiwen.com/subject/qpzzirtx.html