TypeScript中 interface、泛型

interface:

interface PersonInterfact {
	name : string,
	age : number,
	speak(n : number) : void
}
// 定义类
class Person implements PersonInterfact {
	constructor(
		public name : string,
		public age : number
	) { }
	speak(n : number) : void {
		for (let i = 0; i < n; i++) {
			console.log(`你好,我叫${this.name},我的年龄是${this.age}`);
		}
	}
}
const p1 = new Person('jia', 18)
p1.speak(2)//2 你好,我叫jia,我的年龄是18. 2是打印两次的意思

interface UserInterface {
	name : string,
	readonly gender : string,
	age ?: number,
	run : (n : number) => void
}
// 定义对象
const user : UserInterface = {
	name: 'jia',
	gender: '女',
	age: 18,
	run(n) {
		console.log(`奔跑了${n}米`);
	}
}

// 接口之间的继承
interface NameInterface {
	name : string
}
// 接口可重复定义
interface NameInterface {
	color : string
}
interface GoodsInterface extends NameInterface {
	unit : number
}
const goods : GoodsInterface = {
	name: '铅笔',
	color: 'blue',
	unit: 1
}

泛型:

function logoData<T, U>(data1 : T, data2 : U) : T | U {
	// Date.now() % 2 ? console.log(data1) : console.log(data2);
	return Date.now() % 2 ? data1 : data2;
}
logoData<string, number>('dfkgjh', 33)
logoData<number, boolean>(11, false)

interface AInterface<T> {
	name : string,
	age ?: number,
	info : T
}
type JobInfo = {
	title : string,
	company : string
}
let p : AInterface<string> = {
	name: 'aa',
	info: 'sjdf'
}
let f : AInterface<JobInfo> = {
	name: 'aa',
	info: {
		title: 'xlkvm',
		company: "kdjfgkj"
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值