xccjk / x-blog

学习笔记
18 stars 2 forks source link

Typescript #99

Open xccjk opened 1 year ago

xccjk commented 1 year ago

如何使用Typescript来定义一个对象

定义一个已知对象:

interface Person {
    name: string
    age: number
}

const user: Person = {
    name: 'xcc',
    age: 20
}

定义一个复杂的对象:

interface Person {
    name: string
    age: number
    city: {
        address: string
        code: number
    }
}

const user: Person = {
    name: 'xcc',
    age: 20,
    city: {
        address: '武汉光谷',
        code: 430000
    }
}

希望对象有的属性可传可不传时:

// 可选属性
interface Person {
    name: string
    age: number
    sex?: boolean
}

const user: Person = {
    name: 'xcc',
    age: 20,
}

const user1: Person = {
    name: 'xcc,
    age: 20,
    sex: true
}

希望对象属性不可修改时:

// readonly 属性
interface Person {
    readonly id: number
    name: string
    age: number
}

const user: Person = {
    id: 1,
    name: 'xcc',
    age: 20
}

// 修改id,报错Cannot assign to 'id' because it is a read-only property.
user.id = 2
// 修改age
user.age = 30

不清楚对象具体返回了多少对象,只定义了已知字段的类型时:

interface Person {
    name: string
    age: number
    [propName: string]: any
}

const user: Person = {
    name: 'xcc',
    age: 20
}

const user1: Person = {
    name: 'xcc',
    age: 20,
    sex: true
}

当我想对类型进行扩展时:

// 扩展单个类型
interface Person {
    name: string
    age: number
}

interface User extends Person {
    sex: boolean
}

const user: User = {
    name: 'xcc',
    age: 20,
    sex: true
}

// 扩展多个类型
interface Person {
    name: string
    age: number
}

interface Sex {
    sex: boolean
}

interface User extends Person, Sex  {}

const user: User = {
    name: 'xcc',
    age: 20,
    sex: true
}

当我想对多个类型取交集时:

interface Person {
    name: string
    age: number
}

interface Sex {
    sex: boolean
}

type User = Person & Sex

const user: User = {
    name: 'xcc',
    age: 20,
    sex: true,
}
xccjk commented 1 year ago

什么是Typescript类型

类型简单来说就是几种基础类型+符合类型组成的,包含stringnumberbooleanobjectfunction...

类型的区别:

通过类型检查,可以检测指定类型的操作是否正确,对能保证对某种类型只做该类型允许的操作,这就叫做类型安全。

类型检查是为了保障类型安全


类型检查可以在几个阶段做:

动态类型检查

在运行时做类型检查,源码不保留类型信息,对变量赋值、做任何操作都是可以的,灵活性高

静态类型检查

在运行前的编译期做类型检查,源码保留类型信息,声明变量要指定类型,对变量做的操作要和类型匹配。

静态类型在前期需要做类型定义,会增加一定的开发难度。但是可以更好的保证代码的健壮性