vue + typescript 中使用 interface
interface 是什么?TypeScript检查变量类型,判断一个类型的一个关键方法就是interface(使用特定的结构、形状或者特征来分类)<template><div class="User">&amp
·
interface 是什么?
TypeScript检查变量类型,判断一个类型的一个关键方法就是interface
(使用特定的结构、形状或者特征来分类)
<template>
<div class="User">
<h1>登录</h1>
<!-- 渲染各种新建项目 -->
<router-view />
</div>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
//interface 验证的对象必须符合objValidate的条件
interface objValidate{
name:String;
count: String | Number;
age?:Number;//age 被定义为可选属性,那么在传对象的时候age就可有可无。
readonly sex:Boolean;//只读属性,一旦被赋值,不能修改
}
@Component
export default class User extends Vue{
private mounted(){
let obj = {
name:'孙章',
count:1
}
let obj2:objV = {
name:'孙章',
count:1,
age:3,
sex:true
}
// 错误类型 count 报错
// let obj = {
// name:'孙章',
// count:{}
// }
this.changeObj(obj);
}
// obj2.sex = false; //报错
//changeObj方法传入的参数必须符合objValidate的条件
private changeObj(obj:objValidate){
console.log(obj.name);
console.log(obj.count);
}
}
</script>
interface
只是用在TypeScript编译的时候,编译完成后就会删除。不会在编译完成后的JavaScript文件中存在。
//编译后
function changeObj (obj){
console.log(obj.name);
console.log(obj.count);
}
更多推荐
已为社区贡献14条内容
所有评论(0)