TypeScript 使用笔记

小问题 1

ts 报错默认使用 vscode locale 语言,这样可能不太容易在 google 中查询报错原因,使用如下命令将报错提示设置为英文

1
tsc --locale en

unkown 相关类型报错,大概率需要使用 as 关键字进行具体化

小 tips1

使用仅含类型的导入导出语法

推荐使用仅含类型的导入和导出形式的语法可以避免潜在的 “仅含类型的导入被不正确打包” 的问题,写法示例如下:

1
2
import type { SomeThing } from './some-module.js'
export type { SomeThing }

type 和 interface 异同

两者其实非常相似,许多情况下两者都可以用,相较来说,interface 更适合直接拓展属性,具体可见如下例子

扩展 interface

1
2
3
4
5
6
7
8
9
10
11
interface Animal {
name: string
}

interface Bear extends Animal {
honey: boolean
}

const bear = getBear()
bear.name
bear.honey

通过交叉符扩展 type

1
2
3
4
5
6
7
8
9
10
11
type Animal = {
name: string
}

type Bear = Animal & {
honey: boolean
}

const bear = getBear()
bear.name
bear.honey

向 interface 中添加属性

1
2
3
4
5
6
7
8
9
10
interface Window {
title: string
}

interface Window {
ts: TypeScriptAPI
}

const src = 'const a = "Hello World"'
window.ts.transpileModule(src, {})

type 创建后无法更改

1
2
3
4
5
6
7
8
9
type Window = {
title: string
}

type Window = {
ts: TypeScriptAPI
}

// Error: Duplicate identifier 'Window'.

官方具体说明