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"
}
}
