使用.style后,typescript报“ Property 'style' does not exist on type 'Element'. ”
vue是可以执行,并没有报错。但typescript的错误是一个强迫症患者不想看到的。
虽然可以直接写在@Component或是vue.extend里面让typescript不检测,但这样就不是使用typescript的初衷了。
const slidebody = this.$refs.slidebody as HTMLElement;
slidebody.style.width = window.innerWidth * this.tabs.length + 'px';
这样写可以使用style typescript不报错
使用的vs code,编辑器里可以检查错误
// computed start---------------
private _selectedLabel: string = '';
public get selectedLabel(): string {
return this.tabs[this.index].label;
}
public set selectedLabel(news: string) {
this._selectedLabel = news;
}
此种写法不会报错,相当于
// ------
selectedLabel: {
get() {
return this.tabs[this.index].label
},
set(newVal) {
this.index = this.tabs.findIndex((value) => {
return value.label === newVal
})
}
}
// ----------------分隔线-------------------
花了几天时间,把自己的代码风格纠正了一下,
最开始写js的时候用eslint,然后用了一下standardjs,standardjs开箱即用,也确实不错,但还是被我抛弃了,现在主要是在项目中配置eslint+tslint。
编辑器里面是用的eslint做代码风格检查,Prettier来格式化代码。
配置的时候有出了点小问题,在.eslintrc.js文件rules里面设置下面配置
"prettier/prettier": "off"
经常是vscode自动格式化的代码风格与vue eslint检查对不上,单引号,无分号,强制分号这三条问题最多。
有时间把代码风格这块做一下总结,好在工作中统一代码风格。
这或许是每个前端人员都喜欢看到的
Type checking and linting in progress...
App running at:
- Local: http://localhost:8080/
- Network: http://192.168.0.104:8080/
No type errors found
No lint errors found
Version: typescript 3.1.6, tslint 5.12.1
Time: 1866ms
// ----------------分隔线-------------------
关于$refs的问题,按vue的写法在typescript中会报如下错误
Element implicitly has an 'any' type because type 'Element | Element[] | Vue | Vue[]' has no index signature.
在typescript中用必须要先建立一个变量,在后面在取值,如果是component数组,先建立component数组,在后面在传入数组索引取值。
const el: any = this.$refs.component
const instance: any = el[current]
// ----------------分隔线-------------------
场景:
使用了mixins之后,里面有些对象可能是组件里面定义的,但mixins没有定义,可能会报错,这时就可以使用
// @ts-ignore
注释功能。这些注释是一种轻量级的方法来抑制下一行中出现的任何错误。例如,在以下代码中,TypeScript 通常会报告 console.log 声明不可访问。在 TypeScript 2.6 中, // @ts-ignore 会完全忽略注释。
如果定义下划线开头的方法,这时ts就会报错,这时可以使用
// tslint:disable-line
typescript中 get set存取器的写法
private _selectedLabel: string = '' // tslint:disable-line
public get selectedLabel(): string {
this._selectedLabel = this.tabs[this.index].label
return this._selectedLabel
}
public set selectedLabel(news: string) {
this.index = this.tabs.findIndex(value => {
return value.label === news
})
}