https://www.typescriptlang.org/docs/handbook/2/everyday-types.html
primitives 类型
// Boolean类型只有true 和 false 两个值
let isValid: boolean = false;
//Number类型
let n: number = 100
//String类型
let str: string = "hello"
The type names
String
,Number
, andBoolean
(starting with capital letters) are legal, but refer to some special built-in types that will very rarely appear in your code. Always usestring
,number
, orboolean
for types.类型名称是大写字母开头,通常是只内置类型,但是在代码中使用使用,永远是 string,number 和 boolean
symbol
// symbol,Es6引入的原始数据类型,表示独一无二的值,通过Symbol()函数生成
// There is a primitive in JavaScript used to create a globally unique reference via the function Symbol():
// Symbol 函数可以接受字符串作为参数,表示对 Symbol 实例的描述
const firstName = Symbol("name");
const secondName = Symbol("name");
console.log(typeof firstName,typeof secondName)
firstName === secondName //error 报错

也可以作为对象的key,或用于计算属性:
//Just like strings, symbols can be used as keys for object properties.
const sym = Symbol();
let obj = {
[sym]: "value",
};
console.log(obj[sym]); // "value"
//Symbols can also be combined with computed property declarations to declare object properties and class members.
const getClassNameSymbol = Symbol();
class C {
[getClassNameSymbol]() {
return "C";
}
}
let c = new C();
let className = c[getClassNameSymbol](); // "C"
bigint
From ES2020 onwards, there is a primitive in JavaScript used for very large integers, BigInt
:
// ES2020开始引入的一个原始数据类型,也是js的第8个数据类型
// 两种创建方式:
// 1.Creating a bigint via the BigInt function
const oneHundred: bigint = BigInt(100);
// 2.Creating a BigInt via the literal syntax
const anotherHundred: bigint = 100n;
Arrays
typescript中有两种方式创建数组:
// T[]
const list: (string | number)[] = [1,2,'3']; //[1, 2, "3"]
// Array<T>
const arr: Array<string> = ['a','b'] // ['a','b']
Tuple
Enum
Any
任何类型,相当于没有类型。
When a value is of type any
, you can access any properties of it (which will in turn be of type any
), call it like a function, assign it to (or from) a value of any type, or pretty much anything else that’s syntactically legal:
let obj: any = { x: 0 };
// 不会进行类型检查,但是运行时会报错,如:obj.foo is not a function
obj.foo();
obj();
obj.bar = 100;
obj = "hello";
const n: number = obj;
禁用隐式any, 将noImplicitAny
编译选项设为true:
// tsconfig.json
{
"compilerOptions": {
"noImplicitAny":true
}
}
//ok
function Log1(str: string){
}
//ok
function Log2(str: any){
}
// error
function Log3(str){
}

Unknown
https://juejin.cn/post/6844903866073350151
https://zhuanlan.zhihu.com/p/104296850
TypeScript 3.0中引入的 unknown 类型也被认为是 top type ,但它更安全。与 any 一样,所有类型都可以分配给unknown。
let uncertain: unknown = 'Hello'!;
uncertain = 12;
uncertain = { hello: () => 'Hello!' };
我们只能将 unknown 类型的变量赋值给 any 和 unknown:
let uncertain: unknown = 'Hello'!;
let notSure: any = uncertain;
any 和 unknown 的最大区别是, unknown 是 top type (任何类型都是它的 subtype) , 而 any 即是 top type, 又是 bottom type (它是任何类型的 subtype ) ,这导致 any 基本上就是放弃了任何类型检查
unknow类型断言:
function getString() {
return 'helllo world'
}
const str: unknown = getString();
//str.toUpperCase(); // Error: Object is of type 'unknown'
(str as string).toUpperCase() //ok
void
void 类型像是与 any 类型相反,它表示没有任何类型。当⼀个函数没有返回值时,可以指定其为void类型:
// 通常void可以省略
function noReturnFunc(): void{
console.log("noReturnFunc")
}
Never类型
表示永不存在的值。例如,抛出异常函数的返回类型。
function throwErrror(): never{
throw new Error("Sorry, get error")
}
null and undefined
//JavaScript has two primitive values used to signal absent or uninitialized value: null and undefined.
let uType: undefined = undefined;
let nType: null = null;
在Typescript使用这两个类型时,具体行为取决于 strictNullChecks 选项是否开启,推荐 true, 默认false
当 strictNullChecks 为 false 时:
function doSomething(x: string | undefined) {
//不会提示编译错误,但是运行时报错
console.log(x.toUpperCase())
}
doSomething(undefined)
当为 true时, 编辑器为提示错误:

修正的方案是:
function doSomething(x: string | undefined) {
//console.log(x.toUpperCase()) //对象可能为“未定义”。ts(2532)
console.log(x?.toUpperCase()) //HELLO
console.log(x!.toUpperCase()) //HELLO
}
doSomething("hello")
当然,此时如果传参为undefined时,虽然编译不会报错,但是运行时 !断言会报错,因为断言错误。
function doSomething(x: string | undefined) {
//console.log(x.toUpperCase()) //对象可能为“未定义”。ts(2532)
console.log(x?.toUpperCase()) //undefined
console.log(x!.toUpperCase()) //报错
}
doSomething(undefined)
Object Types
Union Types
Literal Types
类型别名和接口
Differences Between Type Aliases and Interfaces