stringnumberbooleannullundefinedsymbolbigint
类型名称 String 、Number、Boolean 等(以大写字母开头)是合法的,但指的是一些很少出现在代码中的特殊内置类型(包装类对象)
始终使用 string 、number、boolean 作为类型
可以通过非空断言运算符 ! 断言一个变量不是 null 或 undefined 类型
function liveDangerously(x?: number | null) {
console.log(x!.toFixed());
}
null 或 undefined,防止 TS 抱怨null 或 undefined,会报错元素类型[]:如 number[]Array<元素类型>:使用泛型,如 Array<number>[元素1类型, 元素2类型, ...]:如 [number, string]function 函数名(形参1: 类型1, 形参2: 类型2): 返回值类型 {
函数体
}
undefined),返回值类型使用 void当函数出现在 TypeScript 可以确定如何调用它的位置时,该函数的参数将自动指定类型:
;["Alice", "Bob", "Eve"].forEach(s => { // 可以确定 s 的类型是字符串
console.log(s.toUpperCase())
})
{
键1: 类型1,
键2: 类型2
}
, 或 ;(如果不在一行 ; 可以省略)分割,最后一个键后面的 , 或 ; 可加可不加对象类型还可以指定它们的部分或全部属性是可选的,属性名称后添加一个 ? 即可:
{
键1: 类型1,
键2?: 类型2
}
读取时,该值可能为 undefined
{
键1: 类型1,
键2: 类型2,
[k: PropertyKey]: 类型
}
any / unknow全集,表示任意类型
any:任意类型,TS 不检查类型。当值的类型为 any 时,可以访问它的任何属性、像函数一样调用它、将其分配给(或从)任何类型的值unknow:未知类型,TS 完全never空集,表示决不可能
类型1 | 类型2 | ...
并集
类型1 & 类型2 & ...
交集
let oneOrTwo: 1 | 2 = 1
// oneOrTwo 只能是 1 或 2
实际 TS 的 boolean 类型就是通过字面量类型和联合类型实现的
type boolean = true | false
type PropertyKey = string | number | symbol
as constconst req = { url: "https://example.com", method: "GET" }
// req 的类型是 { url: string, method: string }
可以通过 as const 将类型指定为字面量类型,而不是更通用的类型:
const req = { url: "https://example.com", method: "GET" as const }
// req 的类型是 { url: string, method: "GET" }
// 或者作用于整个对象
const req = { url: "https://example.com", method: "GET" } as const
// req 的类型是 { url: "https://example.com", method: "GET" }