ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

10. 类型计算入门(描述类型的小工具)

2022-03-08 19:03:00  阅读:124  来源: 互联网

标签:10 入门 ... ## tsxtype 类型 type any string


# 描述类型的小工具



观察所有Typescritp提供的类型下小工具,思考这个问题?

- 类型是可以被计算的吗?



内容

- Partial\<Type\>
- Required\<Type\>
- Readonly\<Type\>
- Record\<Keys,Type\>
- Pick\<Type, Keys\>
- Omit\<Type, Keys\>
- Exclude\<Type, ExcludedUnion\>
- Extract\<Type, Union\>
- NonNullable\<Type\>
- Parameters\<Type\>
- ConstructorParameters\<Type\>
- ReturnType\<Type\>
- InstanceType\<Type\>
- ThisParameterType\<Type\>
- OmitThisParameter\<Type\>
- ThisType\<Type\>
- Intrinsic String Manipulation Types
- Uppercase\<StringType\>
- Lowercase\<StringType\>
- Capitalize\<StringType\>
- Uncapitalize\<StringType\>

## 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<Todo>) {
return { ...todo, ...fieldsToUpdate };
}


const todo1 = {
title: "organize desk",
description: "clear clutter",
};

const todo2 = updateTodo(todo1, {
description: "throw out trash",
})
```

源码怎么实现 Partial?

```tsx
type Partial<T> = {
[P in keyof T]?: T[P];
}
```



## Required

```tsx
interface Props {
a?: number;
b?: string;
}


const obj: Props = { a: 5 };

const obj2: Required<Props> = { a: 5 };

// Error : Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'

```

源码如何实现?

```tsx
type Required<T> = {
[P in keyof T]-?: T[P];
};

```



## Readonly



```tsx
interface Todo {
title: string;
}

const todo: Readonly<Todo> = {
title: "Delete inactive users",
};

todo.title = "Hello";
// Error : Cannot assign to 'title' because it is a read-only property.
```

源码怎么实现?

```tsx
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
```



## Record



```tsx
interface CatInfo {
age: number;
breed: string;
}


type CatName = "miffy" | "boris" | "mordred";

const cats: Record<CatName, CatInfo> = {
miffy: { age: 10, breed: "Persian" },
boris: { age: 5, breed: "Maine Coon" },
mordred: { age: 16, breed: "British Shorthair" },
};

cats.boris;

const cats: Record<CatName, CatInfo>
```

源码怎么实现?

```tsx
type Record<K extends keyof any, T> = {
[P in K]: T;
};

```





## Pick



```tsx
interface Todo {
title: string;
description: string;
completed: boolean;
}

type TodoPreview = Pick<Todo, "title" | "completed">;

const todo: TodoPreview = {
title: "Clean room",
completed: false,
};

todo;
//const todo: TodoPreview
```

源码怎么实现?

```tsx
type Pick<T, K extends keyof T> = {
[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<string | number | (() => void), Function>;

//type T2 = string | number


```

源码怎么实现?

```tsx
type Exclude<T, U> = T extends U ? never : T;
```



## Omit(英文:省略)

```tsx
interface Todo {
title: string;
description: string;
completed: boolean;
createdAt: number;
}

type TodoPreview = Omit<Todo, "description">;

const todo: TodoPreview = {
title: "Clean room",
completed: false,
createdAt: 1615544252770,
};

todo;

// const todo: TodoPreview



type TodoInfo = Omit<Todo, "completed" | "createdAt">;

const todoInfo: TodoInfo = {
title: "Pick up kids",
description: "Kindergarten closes at 5pm",
};

todoInfo;

// const todoInfo: TodoInfo

```

源码怎么实现?

```tsx
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>
```





## Extract

```tsx
type T0 = Extract<"a" | "b" | "c", "a" | "f">;

// type T0 = "a"
type T1 = Extract<string | number | (() => void), Function>;

// type T1 = () => void
```



源码怎么实现?

```tsx
type Extract<T, U> = T extends U ? T : never;
```





## NonNullable

```tsx
type T0 = NonNullable<string | number | undefined>;

// type T0 = string | number
type T1 = NonNullable<string[] | null | undefined>;

// type T1 = string[]
```

源码怎么实现?

```tsx
type NonNullable<T> = 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<<T>(arg: T) => T>;

//type T2 = [arg: unknown]

type T3 = Parameters<typeof f1>

//type T3 = [arg: {
// a: number;
// b: string;
//}]


```

源码怎么实现?

```tsx
type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;
```



## ConstructorParameters

```tsx
type T0 = ConstructorParameters<ErrorConstructor>;

//type T0 = [message?: string]
type T1 = ConstructorParameters<FunctionConstructor>;

//type T1 = string[]
type T2 = ConstructorParameters<RegExpConstructor>;

//type T2 = [pattern: string | RegExp, flags?: string]
type T3 = ConstructorParameters<any>;

//type T3 = unknown[]
type T4 = ConstructorParameters<Function>;
// 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<T extends abstract new (...args: any) => 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>() => T>;

//type T2 = unknown
type T3 = ReturnType<<T extends U, U extends number[]>() => T>;

//type T3 = number[]
type T4 = ReturnType<typeof f1>;

// type T4 = { a: number; b: string; }
type T5 = ReturnType<any>;

// type T5 = any
type T6 = ReturnType<never>;

// type T6 = never
type T7 = ReturnType<string>;
// Type 'string' does not satisfy the constraint '(...args: any) => any'.
//type T7 = any

type T8 = ReturnType<Function>;
// 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<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;
```



## InstanceType

```tsx

class C {
x = 0;
y = 0;
}

type T0 = InstanceType<typeof C>;

// type T0 = C

type T1 = InstanceType<any>;

// type T1 = any
type T2 = InstanceType<never>;

// type T2 = never
type T3 = InstanceType<string>;
// Type 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.
//type T3 = any

type T4 = InstanceType<Function>;
// 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<T extends abstract new (...args: any) => 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<typeof toHex>) {
return toHex.apply(n);
}
```



源码如何实现?

```tsx
type ThisParameterType<T> = T extends (this: infer U, ...args: any[]) => any ? U : unknown;
```



## OmitThisParameter



```tsx
function toHex(this: Number) {
return this.toString(16);
}

const fiveToHex: OmitThisParameter<typeof toHex> = toHex.bind(5);

// const fiveToHex = () => string

console.log(fiveToHex());
```



源码如何实现?

```tsx
type OmitThisParameter<T> = unknown extends ThisParameterType<T> ? T : T extends (...args: infer A) => infer R ? (...args: A) => R : T;
```





## ThisType



```tsx
type ObjectDescriptor<D, M> = {
data?: D;
methods?: M; // Type of 'this' in methods is D & M
};

function makeObject<D, M>(desc: ObjectDescriptor<D, M>): 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<T> { }
```

Why?



## Uppercase / Lowercase



uppercase的例子:

```tsx

type Greeting = "Hello, world"
type ShoutyGreeting = Uppercase<Greeting>

// type ShoutyGreeting = "HELLO, WORLD"

type ASCIICacheKey<Str extends string> = `ID-${Uppercase<Str>}`
type MainID = ASCIICacheKey<"my_app">

// type MainID = "ID-MY_APP"

```

lowercase的例子:

```tsx
type Greeting = "Hello, world"
type QuietGreeting = Lowercase<Greeting>

// type QuietGreeting = "hello, world"

type ASCIICacheKey<Str extends string> = `id-${Lowercase<Str>}`
type MainID = ASCIICacheKey<"MY_APP">

// type MainID = "id-my_app"
```

源码如何实现?

```tsx

/**
* Convert string literal type to uppercase
*/
type Uppercase<S extends string> = intrinsic;

/**
* Convert string literal type to lowercase
*/
type Lowercase<S extends string> = intrinsic;

/**
* Convert first character of string literal type to uppercase
*/
type Capitalize<S extends string> = intrinsic;

/**
* Convert first character of string literal type to lowercase
*/
type Uncapitalize<S extends string> = intrinsic;


```





## 总结



- 类型是可以计算的吗?
- &
- -
- ?
- infer
- ……

标签:10,入门,...,##,tsxtype,类型,type,any,string
来源: https://www.cnblogs.com/anans/p/15981972.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有