变量的定义:
const str: string = 'a'; // 定义字符串
const num: number = 1; // 定义数字
const arr: string[] = ['a', 'b']; // 定义字符串数组
const arr1: (string | number)[] = ['a', 'b', 1]; // 定义联合类型数组
接口的使用:
// 定义对象接口
interface IObj {
id: number; // 确定属性
title?: string; // 可选属性
[proName: string]: any; // 任意属性
}
const obj: IObj = {
id: 1,
title: '文章',
fn: function() {},
a: 1,
b: 's'
}
// 定义数组对象
const list: IObj[] = [
{id: 1, title: '文章1'}
{id: 2, title: '文章2'}
]
// 定义函数类型
const fn1 = (num1: number, num2: number): number => {
return num1 + num2
}
fn1(10, 20)
// 定义无返回函数类型
const fn2 = (num1: number, num2: number): void=> {
...
}
fn2(10, 20)
// 通过接口定义函数类型
interface IFn {
(num1: number, num2: number): number
}
const fn3:IFn = (num1, num2) => {
return num1 + num2
}
fn3(10, 20)
泛型:在定义时不指定数据类型,而是在使用时指定,相当于传了一个参数
const numArr: Array<number> = [1, 2]
const strArr: Array<string> = ['a', 'b']
// 函数泛型,泛型变量T可表示任何类型
function arrMake<T>(ele1: T, ele2: T): T[] {
return [ele1, ele2]
}
const arrMake = <T,>(ele1: T, ele2: T): T[] => { // 箭头函数写法
return [ele1, ele2]
}
arrMake<string>('a', 'b')
arrMake<number>(1, 2)
arrMake<string | number>(1, 2, 'a')
// 泛型约束
interface ILength { // 对泛型进行约束,要求泛型必须有length属性
length: number
}
function getLength<T extends ILength>(a: T): number {
return a.length
}
const getLength = <T extends ILength>(a: T): number => { // 箭头函数写法
return a.length
}
getLength<string>('hello') // 5
getLength<number[]>([1, 2, 3]) // 3
getLength<number>(1) // 报错
// 通过接口使用泛型来定义函数(写法一)
interface IFn {
<T>(a: T, b: T): boolean
}
const fn1: IFn = <T,>(x: T, y: T) => {
return x === y
}
fn1<number>(10, 20)
// 通过接口使用泛型来定义函数(写法二)
interface IFn<T> {
(a: T, b: T): boolean
}
const fn2: IFn<number> = <T,>(x: T, y: T) => {
return x === y
}
fn2(10, 20)