当前位置: 首页 > news >正文

typeScript基础(类型)

在JavaScript中,你需要写单元测试来测试这些东西,但TypeScript可以自动检查它们。所以在某种意义上,TypeScript的类型就像轻量级的单元测试,在你每次保存(编译)代码的时候都会运行。(当然,这个比喻是简化的。你还是应该用TypeScript写测试!)

1.类型,只读属性,映射类型

类型检查,可以确保一个函数的输入和输出是正确类型

创建一个类型

 type Todo = {id: numbertext: stringdone: boolean}

ts检查语法:变量名 : 类型名

首先,我们指定toggleTodo()的输入必须是Todo。我们通过在参数todo旁边添加:Todo来做到这一点。

 // Parameter "todo" must match the Todo typefunction toggleTodo(todo: Todo) {// ...}

接下来,我们指定toggleTodo()的返回类型也必须是Todo。我们通过在参数列表后添加:Todo来做到这一点。

 // The return value must match the Todo typefunction toggleTodo(todo: Todo): Todo {// ...}

只读属性 readonly 防止属性被修改

就是在定义的类型所有属性前面加 readonly

Readonly< ... >映射类型,将一种类型转换成另一种类型

 type Todo = {readonly id: numberreadonly text: stringreadonly done: boolean}

上面的代码等价于:

 
// Readonly<...> makes each property readonlytype Todo = Readonly<{id: numbertext: stringdone: boolean}>

补充:Required<...> , partial<...>

2.数组类型,字面量类型,交叉类型

数组类型

我们可以通过添加[]来指定一个数组类型。我们也可以将一个数组设置为只读的。

 function completeAll(todos: readonly Todo[]): Todo[] {// ...}

在TypeScript中,你可以在指定一个类型的某个属性时使用精确的值(如true或false)。这被称为字面量类型.

type CompletedTodo = Readonly<{id: numbertext: stringdone: true}>

交叉类型:可以覆盖一些属性,可以减少重复代码

使用 & 符号(类型运算符)来创建两种类型的交集类型。例如:交叉类型A&B是一个具有A和B的所有属性的类型

如果第二种类型比第一种类型更具体,那么第二种类型将覆盖第一种

 type A = { foo: boolean }type B = { foo: true }// This intersection type…type AandB = A & B// …is equivalent to:type AandB = { foo: true }type Todo = Readonly<{id: numbertext: stringdone: boolean}>// Override the done property of Todotype CompletedTodo = Todo & {readonly done: true}

3.联合类型和可选属性

union types联合类型

使用语法A | B来创建一个联合类型,它表示一个类型是A或B。

type Place = 'home' | 'work' | { custom: string }// They all compileconst place1: Place = 'home'const place2: Place = 'work'const place3: Place = { custom: 'Gym' }const place4: Place = { custom: 'Supermarket' }type Todo = Readonly<{id: numbertext: stringdone: booleanplace: Place}>

当联合类型与条件语句(如if/else)相结合时,其功能非常强大。

  • 如果我们有一个联合类型的变量(比如说place)...

  • 并在if/else中检查其值...

  • 那么TypeScript就会对变量在if/else的每个分支的可能值进行智能处理。

可选属性

属性名称后面添加一个问号(?)来使该属性成为可选项。

type Foo = {// bar is an optional property because of "?"bar?: number
}
// These will both compile:
// bar can be present or missing
const a: Foo = {}
const b: Foo = { bar: 1 }

4.泛型

基础泛型

function makeState<S>() {let state: Sfunction getState() {return state}function setState(x: S) {state = x}return { getState, setState }
}

可以把 <S> 看作是你在调用该函数时必须传入的另一个东西。 但你不是传递一个值,而是传递一个类型给它

例如,当你调用makeState()时,你可以把类型数字number 作为 S传递。// It sets S as number
makeState<number>()

注意: 我们称 makeState<S>() 为 "泛型函数",因为它实际上是泛型的--你可以选择让它只包含数字或只包含字符串。如果它接受一个类型参数,你就知道它是一个通用函数

参数命名,随意,通常人们使用一个词的第一个字母来描述该类型所代表的内容

常见以下名称:

  • T (代表 “T”ype)

  • E (代表 “E”lement)

  • K (代表 “K”ey)

  • V (代表 “V”alue)

extends:

解决办法: 当你声明 makeState(),时,你把类型参数 <S> 改为 <S extends number | Œstring>. 这是你唯一需要做的改变。

function makeState<S extends number | string>()

通过这样做,当你调用makeState()时,你只能将数字、字符串或任何其他扩展了数字或字符串的类型作为S传递。

默认类型        = 类型(如:= number)如果不传参数,默认数字型)

// Set the default type of S as number
function makeState<S extends number | string = number
>()// Don’t need to use <number>
const numState = makeState()
numState.setState(1)
console.log(numState.getState())

泛型就像普通的函数参数 。不同的是,普通函数参数处理的是 ,而泛型处理的是类型参数

// Set the default type of T
function genericFunc<T = number>()
// T will be number inside the function
genericFunc()

也可以创建一个接受多个类型参数的通用函数

function makePair<F, S>() {let pair: { first: F; second: S }function getPair() {return pair}function setPair(x: F, y: S) {pair = {first: x,second: y}}return { getPair, setPair }
}

甚至可以让第二种类型(S)与第一种类型(F)相关。

// The second parameter S must be either
// boolean or whatever was specified for F
function makePair<F extends number | string,S extends boolean | F
>()
// These will work
makePair<number, boolean>()
makePair<number, number>()
makePair<string, boolean>()
makePair<string, string>()
// This will fail because the second
// parameter must extend boolean | number,
// but instead it’s string
makePair<number, string>()

泛型接口和类型别名

{ first: F, second: S } 变成一个接口或类型别名

首先把配对的类型提取到一个泛型接口(一个接受类型参数的接口)中

interface Pair<F, S> {first: Fsecond: S
}

然后我们可以使用这个接口来声明类型。

function makePair<F, S>() {// Usage: Pass F for A and S for Blet pair: Pair<F, S>// ...
}

或者,我们也可以把它提取到一个通用类型别名中。对于对象类型,类型别名基本上与接口相同,所以你可以使用你喜欢的任何一种。

// Extract into a generic type alias. It’s
// basically identical to using an interface
type Pair<A, B> = {first: Asecond: B
}

泛型类

function makeState<S>() {let state: Sfunction getState() {return state}function setState(x: S) {state = x}return { getState, setState }
}

makeState()变成一个叫做State的泛型类

class State<S> {state: SgetState() {return this.state}setState(x: S) {this.state = x}
}
const numState = new State<number>()
numState.setState(1)
// Prints 1
console.log(numState.getState())

你需要在TypeScript配置(tsconfig.json)上设置 "strictPropertyInitialization": false 以使上述代码能够编译。

相关文章:

  • 2025年人工智能指数报告:技术突破与社会变革的全景透视
  • 011数论——算法备赛
  • webgl入门实例-矩阵在图形学中的作用
  • INFINI Console 系统集群状态异常修复方案
  • 开源的 PDF 文件翻译软件
  • 1.Vue自动化工具安装(Vue-cli)
  • STM32配置系统时钟
  • 【刷题Day21】TCP(浅)
  • [Windows] Adobe Camera Raw 17.2 win/Mac版本
  • 基于一致性哈希算法原理和分布式系统容错机制
  • 探秘C#用户定义类型:突破预定义的边界
  • QML--全局对象Qt
  • 一个Nuxt3 SSR服务端渲染简洁好用的开源个人博客系统 交互设计体验简单 腾讯markdown编辑器 支持drawio画图
  • 杨氏矩阵、字符串旋转、交换奇偶位,offsetof宏
  • 出差像是旅游?
  • Vue3具名插槽用法全解——从零到一的详细指南
  • 树莓派系统中设置固定 IP
  • SMTP发送邮件
  • 聊聊Spring AI Alibaba的FeiShuDocumentReader
  • Gitlab runner 安装和注册
  • 商务部24日下午将举行发布会,介绍近期商务领域重点工作情况
  • 心源性猝死正“猎杀”年轻人,这几招保命法则要学会
  • 世界读书日|全城书香,上海“全民阅读”正在进行时
  • 海南医科大学继续开展部门正职竞聘上岗,致力营造“谁有本事谁来”
  • “女子被前男友泼汽油烧伤案”二审将于22日开庭,一审判12年
  • 海康威视:去年海外主业和机器人等创新业务占比首次超50%