// 通过类型别名(type)来声明对象类型
type infoType = {name: string, age: number}
const info: infoType = {
name: 'lisi',
age: 18
}
// 另一种方式声明对象类型: 接口interface
// 在其中可以定义可选类型 也可以定义只读类型
interface IInfoTypea {
name: string,
age?: number // 可选的
}
const basicInfo: IInfoTypea = {
name: 'lisa',
age: 22
}
// 索引类型
interface IndexLanguage {
[index: number]: string
}
const frontLanguage: IndexLanguage = {
0: 'HTML',
1: 'CSS',
2: 'JavaScript',
3: 'Vue',
// 'abc': '999'
}
interface ILanguageYear {
[name: string]: number
}
const languageYear: ILanguageYear = {
"c":1972,
"Java": 1995,
"JavaScript": 1996,
"TypeScript": 2014
}
// type CalcFn = (n1: number, n2: number) => number
// 可调用的接口
interface CalcFn {
(n1:number, n2: number): number
}
function calc(num1:number, num2: number, calcFn: CalcFn){
return calcFn(num1, num2)
}
const add: CalcFn = (num1, num2) => {
return num1 + num2
}
// 接口的继承
interface ISwim {
swimming: () => void
}
interface IFly {
flying: () => void
}
interface IAction extends ISwim, IFly {
}
const action: IAction = {
swimming() {},
flying() {}
}
// 一种组合类型的方式: 联合类型
type WhyType = number|string
type Direction = "left"|"right"|"center"
// 另一种组合类型的方式:交叉类型
type WType = number & string
interface ISwim {
swimming: () => void
}
interface IFly {
flying: () => void
}
type MyType1 = ISwim | IFly
type MyType2 = ISwim & IFly
const obj1: MyType1 = {
swimming () {
}
}
const obj2: MyType2 = {
swimming(){},
flying(){}
}
typescript接口01(笔记)
最新推荐文章于 2024-07-30 17:19:26 发布