# 描述类型的小工具
观察所有Typescritp提供的类型下小工具,思考这个问题?
- 类型是可以被计算的吗?
内容
- Partial\- Required\- Readonly\- Record\- Pick\- Omit\- Exclude\- Extract\- NonNullable\- Parameters\- ConstructorParameters\- ReturnType\- InstanceType\- ThisParameterType\- OmitThisParameter\- ThisType\- Intrinsic String Manipulation Types
- Uppercase\- Lowercase\- Capitalize\- Uncapitalize\
## Keyof 操作符
```tsx
type Point = { x: number; y: number };
type P = keyof Point;
// type P = "x" | "y"
type Arrayish = { [n: number]: unknown };
type A = keyof Arrayish;
// type A = number
type Mapish = { [k: string]: boolean };
type M = keyof Mapish;
// type M = string | number
```
## Typeof
```tsx
console.log(typeof "xxx") // string
let s = "hello"
let n : typeof s
// n -- string
```
## Partial Type
```tsx
interface Todo {
title: string;
description: string;
}
function updateTodo(todo: Todo, fieldsToUpdate: Partial) {
return { ...todo, ...fieldsToUpdate };
}
const todo1 = {
title: "organize desk",
description: "clear clutter",
};
const todo2 = updateTodo(todo1, {
description: "throw out trash",
})
```
源码怎么实现 Partial?
```tsx
type Partial = {
[P in keyof T]?: T[P];
}
```
## Required
```tsx
interface Props {
a?: number;
b?: string;
}
const obj: Props = { a: 5 };
const obj2: Required = { a: 5 };
// Error : Property 'b' is missing in type '{ a: number; }' but required in type 'Required'
```
源码如何实现?
```tsx
type Required = {
[P in keyof T]-?: T[P];
};
```
## Readonly
```tsx
interface Todo {
title: string;
}
const todo: Readonly = {
title: "Delete inactive users",
};
todo.title = "Hello";
// Error : Cannot assign to 'title' because it is a read-only property.
```
源码怎么实现?
```tsx
type Readonly = {
readonly [P in keyof T]: T[P];
};
```
## Record
```tsx
interface CatInfo {
age: number;
breed: string;
}
type CatName = "miffy" | "boris" | "mordred";
const cats: Record = {
miffy: { age: 10, breed: "Persian" },
boris: { age: 5, breed: "Maine Coon" },
mordred: { age: 16, breed: "British Shorthair" },
};
cats.boris;
const cats: Record
```
源码怎么实现?
```tsx
type Record = {
[P in K]: T;
};
```
## Pick
```tsx
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Pick;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
};
todo;
//const todo: TodoPreview
```
源码怎么实现?
```tsx
type Pick = {
[P in K]: T[P];
};
```
## Exclude
```tsx
type T0 = Exclude<"a" | "b" | "c", "a">;
//type T0 = "b" | "c"
type T1 = Exclude<"a" | "b" | "c", "a" | "b">;
//type T1 = "c"
type T2 = Exclude void), Function>;
//type T2 = string | number
```
源码怎么实现?
```tsx
type Exclude = T extends U ? never : T;
```
## Omit(英文:省略)
```tsx
interface Todo {
title: string;
description: string;
completed: boolean;
createdAt: number;
}
type TodoPreview = Omit;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
createdAt: 1615544252770,
};
todo;
// const todo: TodoPreview
type TodoInfo = Omit;
const todoInfo: TodoInfo = {
title: "Pick up kids",
description: "Kindergarten closes at 5pm",
};
todoInfo;
// const todoInfo: TodoInfo
```
源码怎么实现?
```tsx
type Omit = Pick>
```
## Extract
```tsx
type T0 = Extract<"a" | "b" | "c", "a" | "f">;
// type T0 = "a"
type T1 = Extract void), Function>;
// type T1 = () => void
```
源码怎么实现?
```tsx
type Extract = T extends U ? T : never;
```
## NonNullable
```tsx
type T0 = NonNullable;
// type T0 = string | number
type T1 = NonNullable;
// type T1 = string[]
```
源码怎么实现?
```tsx
type NonNullable = T extends null | undefined ? never : T;
```
## Parameters
```tsx
declare function f1(arg: { a: number; b: string }): void;
type T0 = Parameters<() => string>;
//type T0 = []
type T1 = Parameters<(s: string) => void>;
//type T1 = [s: string]
type T2 = Parameters<(arg: T) => T>;
//type T2 = [arg: unknown]
type T3 = Parameters
//type T3 = [arg: {
// a: number;
// b: string;
//}]
```
源码怎么实现?
```tsx
type Parameters any> = T extends (...args: infer P) => any ? P : never;
```
## ConstructorParameters
```tsx
type T0 = ConstructorParameters;
//type T0 = [message?: string]
type T1 = ConstructorParameters;
//type T1 = string[]
type T2 = ConstructorParameters;
//type T2 = [pattern: string | RegExp, flags?: string]
type T3 = ConstructorParameters;
//type T3 = unknown[]
type T4 = ConstructorParameters;
// Error : Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'.
// Type 'Function' provides no match for the signature 'new (...args: any): any'.
//type T4 = never
```
```tsx
interface ErrorConstructor {
new(message?: string): Error;
(message?: string): Error;
readonly prototype: Error;
}
interface FunctionConstructor {
/**
* Creates a new function.
* @param args A list of arguments the function accepts.
*/
new(...args: string[]): Function;
(...args: string[]): Function;
readonly prototype: Function;
}
interface RegExpConstructor {
new(pattern: RegExp | string): RegExp;
new(pattern: string, flags?: string): RegExp;
(pattern: RegExp | string): RegExp;
(pattern: string, flags?: string): RegExp;
readonly prototype: RegExp;
// Non-standard extensions
$1: string;
$2: string;
$3: string;
$4: string;
$5: string;
$6: string;
$7: string;
$8: string;
$9: string;
lastMatch: string;
}
```
源码怎么实现?
```tsx
type ConstructorParameters any> = T extends abstract new (...args: infer P) => any ? P : never;
```
## ReturnType
```tsx
declare function f1(): { a: number; b: string };
type T0 = ReturnType<() => string>;
//type T0 = string
type T1 = ReturnType<(s: string) => void>;
//type T1 = void
type T2 = ReturnType<() => T>;
//type T2 = unknown
type T3 = ReturnType<() => T>;
//type T3 = number[]
type T4 = ReturnType;
// type T4 = { a: number; b: string; }
type T5 = ReturnType;
// type T5 = any
type T6 = ReturnType;
// type T6 = never
type T7 = ReturnType;
// Type 'string' does not satisfy the constraint '(...args: any) => any'.
//type T7 = any
type T8 = ReturnType;
// Type 'Function' does not satisfy the constraint '(...args: any) => any'.
// Type 'Function' provides no match for the signature '(...args: any): any'.
// type T8 = any
```
源码怎么实现?
```tsx
type ReturnType any> = T extends (...args: any) => infer R ? R : any;
```
## InstanceType
```tsx
class C {
x = 0;
y = 0;
}
type T0 = InstanceType;
// type T0 = C
type T1 = InstanceType;
// type T1 = any
type T2 = InstanceType;
// type T2 = never
type T3 = InstanceType;
// Type 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.
//type T3 = any
type T4 = InstanceType;
// Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'.
// Type 'Function' provides no match for the signature 'new (...args: any): any'.
// type T4 = any
```
源码如何实现?
```tsx
type InstanceType any> = T extends abstract new (...args: any) => infer R ? R : any;
```
## ThisParameterType
```tsx
function toHex(this: Number) {
return this.toString(16);
}
function numberToString(n: ThisParameterType) {
return toHex.apply(n);
}
```
源码如何实现?
```tsx
type ThisParameterType = T extends (this: infer U, ...args: any[]) => any ? U : unknown;
```
## OmitThisParameter
```tsx
function toHex(this: Number) {
return this.toString(16);
}
const fiveToHex: OmitThisParameter = toHex.bind(5);
// const fiveToHex = () => string
console.log(fiveToHex());
```
源码如何实现?
```tsx
type OmitThisParameter = unknown extends ThisParameterType ? T : T extends (...args: infer A) => infer R ? (...args: A) => R : T;
```
## ThisType
```tsx
type ObjectDescriptor = {
data?: D;
methods?: M; // Type of 'this' in methods is D & M
};
function makeObject(desc: ObjectDescriptor): D & M {
let data: object = desc.data || {};
let methods: object = desc.methods || {};
return { ...data, ...methods } as D & M;
}
let obj = makeObject({
data: { x: 0, y: 0 },
methods: {
moveBy(dx: number, dy: number) {
this.x += dx; // Strongly typed this
this.y += dy; // Strongly typed this
},
},
});
obj.x = 10;
obj.y = 20;
obj.moveBy(5, 5);
```
源码如何实现?
```tsx
interface ThisType { }
```
Why?
## Uppercase / Lowercase
uppercase的例子:
```tsx
type Greeting = "Hello, world"
type ShoutyGreeting = Uppercase
// type ShoutyGreeting = "HELLO, WORLD"
type ASCIICacheKey = `ID-${Uppercase}`
type MainID = ASCIICacheKey<"my_app">
// type MainID = "ID-MY_APP"
```
lowercase的例子:
```tsx
type Greeting = "Hello, world"
type QuietGreeting = Lowercase
// type QuietGreeting = "hello, world"
type ASCIICacheKey = `id-${Lowercase}`
type MainID = ASCIICacheKey<"MY_APP">
// type MainID = "id-my_app"
```
源码如何实现?
```tsx
/**
* Convert string literal type to uppercase
*/
type Uppercase = intrinsic;
/**
* Convert string literal type to lowercase
*/
type Lowercase = intrinsic;
/**
* Convert first character of string literal type to uppercase
*/
type Capitalize = intrinsic;
/**
* Convert first character of string literal type to lowercase
*/
type Uncapitalize = intrinsic;
```
## 总结
- 类型是可以计算的吗?
- &
- -
- ?
- infer
- ……