2-1-10&11 TS 类型计算入门(描述类型的小工具)

Posted 沿着路走到底

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2-1-10&11 TS 类型计算入门(描述类型的小工具)相关的知识,希望对你有一定的参考价值。

Keyof 操作符

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

console.log(typeof "xxx") // string

let s = "hello"
let n : typeof s
// n -- string

Partial Type

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

type Partial<T> = 
    [P in keyof T]?: T[P];

Required

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>'

源码实现

type Required<T> = 
    [P in keyof T]-?: T[P];
;

Readonly

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.

源码实现

type Readonly<T> = 
    readonly [P in keyof T]: T[P];
;

Record

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>

源码实现

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

Pick

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

源码实现

type Pick<T, K extends keyof T> = 
    [P in K]: T[P];
;

Exclude

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

源码实现

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

Omit 省略

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

源码实现

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

Extract 提取

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

源码实现

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

NonNullable

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

源码实现

type NonNullable<T> = T extends null | undefined ? never : T;

Parameters

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;
//]

源码实现

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

ConstructorParameters

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











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;

源码实现

type ConstructorParameters<T extends abstract new (...args: any) => any> = T extends abstract new (...args: infer P) => any ? P : never;

ReturnType

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

源码实现

type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;

InstanceType

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

源码实现

type InstanceType<T extends abstract new (...args: any) => any> = T extends abstract new (...args: any) => infer R ? R : any;

ThisParameterType

function toHex(this: Number) 
  return this.toString(16);

 
function numberToString(n: ThisParameterType<typeof toHex>) 
  return toHex.apply(n);

源码实现

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

OmitThisParameter

function toHex(this: Number) 
  return this.toString(16);

 
const fiveToHex: OmitThisParameter<typeof toHex> = toHex.bind(5);
                                   
// const fiveToHex = () => string
 
console.log(fiveToHex());

源码实现

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

ThisType

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);

源码实现

interface ThisType<T>  

Uppercase / Lowercase

uppercase的例子:

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的例子:

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"

源码实现

/**
 * 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;

1

以上是关于2-1-10&11 TS 类型计算入门(描述类型的小工具)的主要内容,如果未能解决你的问题,请参考以下文章

C ++参数包,仅限于具有单一类型的实例?

Angular Library 11:在构建中包含 index.d.ts

Typescript基本类型---下篇

如何计算 ICMP 数据包的往返时间

TS基础语法

typescript入门