typescript类型断言解决一些常见问题

最近在维护一个vue+ts项目的过程中遇到了一些typescript类型报错,简单来讲就是ts在进行类型推断时出现了一些错误,需要我们选择性的使用类型断言来解决报错,下面是我收集到的目前出现错误的情况,后续如果有发现新问题会持续更新。

Property ‘insertRule’ does not exist on type ‘StyleSheet’

这个是我在Vue中开发一个CSS动画时候报的错,具体在下面这段代码中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const style = document.createElement('style');
style.setAttribute('type', 'text/css');
document.head.appendChild(style);
const sheet = style.sheet;

sheet.insertRule(
`@keyframes roller {
from {
top: 0px;
}
to {
top: -${(this.prizeArr.length - 1) * this.itemHeight}px;
}
}`, 0
)

业务需求是动态地往html文档头部增加一个style标签,写入对应的animation的keyframe规则,但是如果像上面这样就会报两个错:

首先看第一个问题,Object is possible null,也就是当我们申明sheet变量时没给它一个确认的类型,那么ts就会进行推断,推断的结果就是sheet是一个null | StyleSheet类型,这个时候调用insertRule方法就会发生类型错误

这个时候当我们确定sheet不会是null时,就可以使用类型断言:

1
2
3
4
5
6
7
8
9
10
(sheet as StyleSheet).insertRule(
`@keyframes roller {
from {
top: 0px;
}
to {
top: -${(this.prizeArr.length - 1) * this.itemHeight}px;
}
}`, 0
)

那么这个时候就会出现第二个错:

Property ‘insertRule’ does not exist on type ‘StyleSheet’

这是因为类型StyleSheet确实缺少addRule和insertRule方法。这些方法是在CSSStyleSheet类型上定义的。

只需要这样修改就可以了:

1
2
3
4
5
6
7
8
9
10
(sheet as CSSStyleSheet).insertRule(
`@keyframes roller {
from {
top: 0px;
}
to {
top: -${(this.prizeArr.length - 1) * this.itemHeight}px;
}
}`, 0
)

Object is possibly ‘null’ for regex

这是在使用正则表达式时会发生的一个错,同样也是因为ts类型推断结果里面包含了null导致不能正确调用变量的方法。

1
const body = /<body.*?>([\s\S]*)<\/body>/.exec(html)[1];

这个时候可以使用非空类型断言来解决:

1
const body = /<body.*?>([\s\S]*)<\/body>/.exec(html)![1];

Property ‘validate’ does not exist on type ‘Vue | Element | Vue[] | Element[]’.

这是一个在vue中会报的错,我们在父组件调用子组件中的方法时,要么使用emit,要么直接调用,就像下面这样

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// 父组件
<template>
<son ref="sonEle"/>
</template>

<script>
// 此处省略一些引入的文件
@Component{}
export default class Parent extends Vue {
created() {
this.$refs.sonEle.play();
}
}
</script>

// 子组件
<template>
// ...
</template>

<script>
// 此处省略一些引入的文件
@Component{}
export default class Parent extends Vue {
play() {
// ...
}
}
</script>

这个时候就会发生ts的类型报错:Property ‘play’ does not exist on type ‘Vue | Element | Vue[] | Element[]’.

同样使用类型断言:

1
(this.$refs.sonEle as Vue & { play: () => null }).play();

如果这个方法在组建内被多次使用,可以使用这个方法:

1
2
3
4
5
computed: {
play(): Vue & { play: () => null } {
return this.$refs.sonEle as Vue & { play: () => null };
}
}
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

扫一扫,分享到微信

微信分享二维码
  • Copyrights © 2015-2021 AURORA_ZXH
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信