// 对象接口类型
interface List {
readonly id:number;
name: string;
// [x:string]:any; //字符串索引签名, 用任意字符串索引List得到任意结果
age?:number; //可选属性 可以有 可以没有
}
interface Result {
data:List[]
}
function render(result:Result){
result.data.forEach(value => {
console.log(value.id, value.name);
// value.id++; 只读属性不能赋值操作
if(value.age){
console.log(value.age)
}
})
}
let result = {
data:[
{id:1, name:"A", sex:'male'}, //多余的字段被允许,鸭式变形法
{id:2,name:"B"}
]
}
// render(result)
render({
data:[
{id:1, name:"A", sex:'male'}, //字面量参数 无法通过类型检查,除非 as类型断言 才能绕过
{id:2,name:"B"}
]
} as Result)
// -----
interface StringArray{
[index:number]:string
}
let chars:StringArray = ["A","B"];
interface Names {
[x:string]:string;
// y:number
[z:number]:string //这里如果设置成number是不行的, 数字类型不能赋值给string类型, 必须是子类型
}
// -----------------------
// 函数接口类型
let add2: (x:number,y:number) => number
interface Add2 {
(x:number, y:number):number
}
// 类型别名
type Add3 = (x:number, y:number) => number
let add4:Add3 = (a,b) => a+b
// 混合接口类型
interface Lib {
():void;
version:string;
doSometh():void;
}
let lib:Lib = (() => {}) as Lib;
lib.version = '1.0'
lib.doSometh = () => {} //这样暴露一个全局的lib, 且是单例
function getLib(){
let lib:Lib = (() => {}) as Lib;
lib.version = '1.0'
lib.doSometh = () => {}
return lib;
}
let lib1 = getLib();
lib1();
lib1.doSometh();