1. 当代码中导入了第三方库的时候,直接编译文件报错。例如以下目录:

1
2
3
4
5
6
.
├── demo.ts
├── node_modules
├── package.json
├── tsconfig.json
└── yarn.lock

其中demo.ts的代码如下:

1
2
3
import { of } from 'rxjs'

of(1, 2, 3).subscribe(x => console.log(x))

用以下方式运行:

1
2
3
4
pixcai@sierra:~/demo|⇒ ./node_modules/.bin/tsc demo.ts
node_modules/rxjs/internal/Observable.d.ts(82,59): error TS2693: 'Promise' only refers to a type,but is being used as a value here.
node_modules/rxjs/internal/types.d.ts(35,84): error TS2304: Cannot find name 'Iterable'.
node_modules/rxjs/internal/types.d.ts(39,6): error TS2304: Cannot find name 'Symbol'.

如果TypeScript装在全局,即npx tsc demo.ts,也是一样。

问题原因tsconfig.json没生效。

解决办法npx tsc -p tsconfig.jsonnpx tsc -p .npx tsc --lib es2015,dom demo.ts

2. document.getElementById()document.querySelector()等函数返回的是Element类型,如果要取某些属性,比如:

1
2
const target = document.querySelector('.target')
target.style.top = '100px'

则会报错:

1
error TS2339: Property 'style' does not exist on type 'Element'.

解决办法:转换为HTMLElement类型,const target = <HTMLElement>document.querySelector('.target')