类型操作
Generics
范型:传递参数的类型Keyof
类型操作符:使用 keyof 操作符来创建新类型Typeof
类型操作符:使用 typeof 操作符来创建新类型Indexed Access Types
索引访问类型:使用Type['a']
语法来访问类型的子类型Conditional Types
条件类型:在类型系统中行为向 if 语句x extends y?true:false
Mapped Types
映射类型:通过在现存类型中映射每个属性来创建类型Template Literal Types
模板字面量类型:通过模板字面量字符串改变属性的映射类型
工具类型
Partial<T>
Required<T>
Readonly<T>
Record<K,T>
Pick<T>
Omit<T>
Exclude<T>
Extract<T>
NonNullable<T>
Parameters<T>
ConstructorParameters<T>
RetureType<T>
InstanceType<T>
ThisParameters<T>
OmitThisParameters<T>
ThisType<T>
字符串的基本操作
Uppercase<StringT>
Lowercase<StringT>
Capitalize<StringT>
Uncapitalize<String>
类型是所有满足某些特征的 JS 值的集合
静态索引签名:
class Foo {
static hello = 'hello'
static world = 1234
static [propName: string]: string | number | undefined
}
// Valid.
Foo['whatever'] = 42
// Has type 'string | number | undefined'
let x = Foo['something']
- 实例索引签名:
class Foo {
hello = 'hello'
world = 1234;
// This is an index signature:
[propName: string]: string | number | undefined
}
let instance = new Foo()
// Valid assigment
instance['whatever'] = 42
// Has type 'string | number | undefined'.
let x = instance['something']
- 检查Promise真值:
async function foo(): Promise<boolean> {
return false
}
async function bar(): Promise<string> {
if (foo()) {
// ~~~~~
// Error!
// This condition will always return true since
// this 'Promise<boolean>' appears to always be defined.
// Did you forget to use 'await'?
return 'true'
}
return 'false'
}
- 检查实例私有属性:
class Foo {
#someMethod() {
//...
}
get #someValue() {
return 100
}
publicMethod() {
// These work.
// We can access private-named members inside this class.
this.#someMethod()
return this.#someValue
}
}
new Foo().#someMethod()
// ~~~~~~~~~~~
// error!
// Property '#someMethod' is not accessible
// outside class 'Foo' because it has a private identifier.
new Foo().#someValue
// ~~~~~~~~~~
// error!
// Property '#someValue' is not accessible
// outside class 'Foo' because it has a private identifier.
- 静态成员私有名称:
class Foo {
static #someMethod() {
// ...
}
}
Foo.#someMethod()
// ~~~~~~~~~~~
// error!
// Property '#someMethod' is not accessible
// outside class 'Foo' because it has a private identifier.
- 模板字符串类型
type Color = 'red' | 'blue'
type Quantity = 'one' | 'two'
type SeussFish = `${Quantity | Color} fish`
// same as
// type SeussFish = "one fish" | "two fish"
// | "red fish" | "blue fish";
declare let s1: `${number}-${number}-${number}`
declare let s2: `1-2-3`
// Works!
s1 = s2
- 属性上的写类型:
class Thing {
#size = 0
get size(): number {
return this.#size
}
set size(value: string | number | boolean) {
let num = Number(value)
// Don't allow NaN and stuff.
if (!Number.isFinite(num)) {
this.#size = 0
return
}
this.#size = num
}
}
空类型 never: 函数不返回
void: 没有返回一个值的函数值的类型