Ts中的类型注解
前两天,有位前端同学尝试进军Ts,然后在写Promise的Ts类型注解时,发现不论怎么写都发生了报错,以至于用上了any也不行。代码如下:
<div class="hello">
<h1>{{ msg }}</h1>
<h2>{{ text }}</h2>
<input type="text" v-model="input" @click="testFun">
</div>
</template>
<script lang="ts">
import { Options, Vue, createDecorator } from 'vue-class-component';
type customObj = { code: number, name: string, age: string}
const Log = createDecorator((options, key) => {
const originMet = options.methods[key]
options.methods[key] = function wrapperMethod(...args:any[]) {
console.log(`Invoked: ${key}(`, ...args, ')')
originMet.apply(this, args)
}
})
@Options({
props: {
msg: String
}
})
export default class HelloWorld extends Vue {
msg!: string
text = 'a'
input = ''
// @Log
testFun():void{
this.showMe(this.input).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
}
@Log
showMe (str:string):Promise<customObj> {
let sth:customObj = { code: 1, name: 'xxx', age: str}
this.text += this.input
return new Promise((resolve: any) => {
if(sth.age.length >= 2){
resolve(sth)
}
})
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
定义一个方法与调用一个方法的区别
Ts对定义一个方法与调用一个方法时,类型注解是有一定的区别的,如果不能好好理解这两者的区别,那么在调用的时候就会不停的保存,影响大了,还会成为《Ts从入门到放弃》。
Ts定义一个方法并调用:
上面这段代码,就是用Ts定义一个funtion ,这是定义一个方法,并调用了该方法,这么看的话,大家都可以看明白,但是当我们在Ts中调用 Promise时,却需要我们绕个弯。点击运行,按F12
Ts中调用 Promise
const data = new Promise()
上面这里,我们调用了一个Promise, 这种行为属于调用一个方法,因为是调用一个方法,所以我们在使用这个方法时,就需要按照这个方法的类型注解来写
这里是Ts中Promise的类型注解,这样看,可能有些看不明白。
但是这并不麻烦。首先我们都知道,Promise是一个异步方法,这个异步方法的是返回一个then的对象属性,可以大致理解为:
const testPromise = function testPromise() {
const obj = {
then: function () {},
catch: function () {},
};
return obj;
};
testPromise().then();
这只是有一个大概的意思,实际上要比这个复杂得多,如果需要深入了解Promise,可以去看别人写的文章。
而用Ts调用Promise的话 为这样
这个方法上面有@Log装饰器,这个装饰器如果存在的话,就无法接收到Promise的返回值。 其实如果不会写的话,用vs code 将鼠标挪到方法中,上面的类型注解直接copy过来就可以用了
type Mytest = string;
showMe(str: Mytest): Promise<Mytest> {
return new Promise((resolve: (value: Mytest) => void) => {
console.log(str);
resolve(str);
});
}
end
本来想好好写的,但是太麻烦了 就这样吧。