TypeScript教程--js引用数据类型

120 阅读3分钟

TypeScript教程

js引用数据类型

说明:ts中数据类型包括js已有的数据类型、ts新增的数据类型,本文讲解js已有的数据类型。

①基本数据类型

  • string

  • number

  • boolean

  • null

  • undefined

  • symbol

  • bigint

②引用数据类型

  • object

  • array

  • function

    ....

引用数据类型

一、object

说明:一个包含属性和方法的复合数据结构

1.基本使用

let object1: { name: string; age: number; say: (text: string) => void };
object1 = {
    name: "张三",
    age: 18,
    say(text) {

    }
}
console.log(typeof object1) //object
let object2: { name: string, age: number, say(text: string): void };
object2 = {
    name: "张三",
    age: 18,
    say(text) {

    }
}

2.可选属性或方法

let object3: { name: string; age?: number; say?: (text: string) => void };
let object4: { name: string; age?: number; say?(text: string): void };
object3 = {
    name: "张三"
}
object4 = {
    name: "张三"
}

3.索引签名(允许动态添加和访问对象属性)

//其中key为索引签名的名称可自定义,后面两个类型为属性和值的类型。
let object5: { [key: string]: number };
object5 = {
    //name:"张三", //TS2322: Type string is not assignable to type number
    age: 8
}
object5["age"]= 10
console.log(object5["age"]) //10
object5.age = 20
console.log(object5.age) //20

4.设置只读属性

let object6: {readonly id:string,name:string}
object6={
    id:"uuid1",
    name:"张三"
}
//object6.id="uuid2" //TS2540: Cannot assign to id because it is a read-only property.
object6.name="李四"

5.访问对象属性的方式

let object7: { [key: string]: string };
object7 = {
    name: "张三"
}
//点运算符(适用于静态属性 编译时确定)
console.log(object7.name) //张三
//方括号运算符(适用于静态或动态属性,运行时确定,可接收特殊字符或变量)
console.log(object7["name"]) //张三
let key = "name"
console.log(object7[key]) //张三

二、array

1.方括号

let array1: number[]
array1 = [1, 2, 3]
console.log(typeof array1) //object
//联合类型
let array3: (number|string)[]
array3=[1,2,3,"hello"]

2.泛型

let array2: Array<number>
array2 = [1, 2, 3]
console.log(typeof array2) //object
//联合类型
let array4: Array<number|string>
array4=[1,2,3,"hello"]

三、函数

1.函数声明

function function1(a: number, b: number): number {
    return a + b
}

备注:输出类型可省略,根据返回语句自动推断,若函数未明确返回,则默认返回类型为void。

2.函数表达式

const function2: (a: number, b: number) => number = function (a, b) {
    return a - b;
};

3.箭头函数

const function3: (a: number, b: number) => number = (a, b) => a * b;

备注

  • js中=>在函数定义时表示函数的具体实现,是es6中引入的定义函数方式。

  • ts中=>在函数类型声明时表示函数的类型,指定函数的参数和返回值类型。

  • 同样可以使用接口(interface)、类型(type)等方式进行函数类型声明。

4.可选参数

function function4(a: string, b?: string): string {
    if (b) {
        return a + ":" + b;
    } else {
        return a;
    }
}
console.log(function4("hello")) //hello 
console.log(function4("hello", "ts")) //hello:ts

备注:可选参数需放在必填参数后面

5.默认参数

function function5(a: string, b: string = "ts"): string {
    return a + ":" + b;
}
console.log(function5("hello")) //hello:ts
console.log(function5("hello", "ts")) //hello:ts

备注:指定默认值的参数是可选的

6.剩余参数

function function6(...numbers: number[]) {
    return numbers.reduce((sum, num) => sum + num, 0)
}
console.log(function6()) //0
console.log(function6(1, 2)) //3

文章首发公众号自学Java教程 欢迎关注解锁更多精彩内容!