一个语言,接口部分能用的灵活,是写好一点代码的基本条件。记录些接口知识点。
ts部分的接口,相比js。在对象属性报错部分,能提供更为具体的报错。
常规用法:
interface IState {
readonly state: number;
findOne(): void;
}
const q: IState = { state: 1,
findOne() {
console.log("findOne");
},
};接口中,只有一个方法时,一般处理方式:
interface Func {
(x: number, y: number, desc?: string): void
}
const sum: Func = function (x, y, desc = '') {
//do something
}
推荐替代方案:
type Func = (x: number, y: number, desc?: string) => void;接口间的extends,和接口的实现implement,跟java很类似,不记录了。
interface和type对比
- type可以声明基本类型别名,联合类型,元组等类型
type Name = string //基本类型别名
type Pet = Cat | Dog //联合类型
type PetArray = [Dog,Cat,Pet] // - type可以获取实例的类型,进行赋值
type B = typeof div;- type其他操作
type NumberOrBoolean = number | boolean;
type Callback<T> = (data:T) => void;
type Coordinates = Pair<number>;
type Tree<T> = T | {left: Tree<T>, right: Tree<T>};- interface可以合并接口,type不行
从结果生成interface/type
- 在线生成,把 json 贴进去就好。 http://json2ts.com/
- 用 typeof
const post = {
id: '123',
title: 'title',
content: 'title',
interact: {
like_count: 100,
view_count: 200,
},
};
type Post = typeof post;
// 这样 Post 就相当于拿到了 post 实例的数据解构定义了typesync 自动帮找引入库的d.ts文件。
Vue 写法
data
直接定义就行
computed 计算属性
get msg(){
return "aaa"+this.message;
}watch
@Watch("child")
writeRandomMethod(val: string,oldVal: string){
if(val === oldVal){
}
}prop
@Prop({ type: [String, Number], required: true }) readonly child!: string | number