关于TS的使用(定义 、接口、泛型等)

12 篇文章 0 订阅
1 篇文章 0 订阅

变量的定义:

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值