markdown 打字稿Cheatsheet

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown 打字稿Cheatsheet相关的知识,希望对你有一定的参考价值。

# Basic Types
## All Basic Type keywords
From https://www.typescriptlang.org/docs/handbook/basic-types.html
```typescript
const bool: boolean = true;
const num: number = 5;
const str: string = 'apple';
const numArr: number[] = [1, 2, 3];
const f: Function = () => 1;

// Tuple
let aTuple: [string, number];
aTuple = ["hello", 10];

// Enum
enum Color {Red, Green, Blue}
enum Color2 {Red = 'red', Green = 'green', Blue = 3}
let c: Color = Color.Green;
let c2: Color2 = Color2.Green;

// Any
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean

// Void
function warnUser(): void {
    alert("This is my warning message");
}

// Null and Undefined
let u: undefined = undefined;
let n: null = null;

// Never
// Function returning never must have unreachable end point
function error(message: string): never {
    throw new Error(message);
}

// Type assertions or Typecasting
let someValue: any = "this is a string";

let strLength: number = (<string>someValue).length;
// Equivalent to the previous line with 'as' syntax
let strLength: number = (someValue as string).length;
```

## Interfaces
Defines an object or class structure
```typescript
interface Timing {
    name: string;
    value: number;
    func: (a: number) => string;
}

const t: Timing = {
    name: 'load',
    value: 5,
    func: (a: number) => 'apple' // function type definition
};

class A implements Timing {
    name: string;
    value: number;

    constructor() {
        this.name = 'name';
        this.value = 5;
    }

    func(a: number) {
        return 'apple';
    }
}

```

## Type Aliases
```typescript
type StringOrNumber = string | number;
```

# Advanced Types
https://www.typescriptlang.org/docs/handbook/advanced-types.html

## Index Types
```typescript
function pluck<T, K extends keyof T>(o: T, names: K[]): T[K][] {
  return names.map(n => o[n]);
}
let person: Person = {
    name: 'Jarid',
    age: 35
};
let strings: string[] = pluck(person, ['name']); // ok, string[]
```

## Index Signatures
Constrain all the keys/values of an object to a certain type.
```typescript
interface Map<T> {
    [key: string]: T;
}
let keys: keyof Map<number>; // string
let value: Map<number>['foo']; // number
```

## Mapped Types
Go even further than index signatures and use rules that apply to a subset of a types properties. See [the advanced types handbook for more info](https://www.typescriptlang.org/docs/handbook/advanced-types.html).

## Type Guards
Used for narrowing union types.

### typeof Type Guards
Can only be used for official types: _These typeof type guards are recognized in two different forms: typeof v === "typename" and typeof v !== "typename", where "typename" must be "number", "string", "boolean", or "symbol". While TypeScript won’t stop you from comparing to other strings, the language won’t recognize those expressions as type guards._
```typescript
function padLeft(value: string, padding: string | number) {
    if (typeof padding === "number") {
        return Array(padding + 1).join(" ") + value;
    }
    if (typeof padding === "string") {
        return padding + value;
    }
    throw new Error(`Expected string or number, got '${padding}'.`);
}
```

### instanceof
Use these for comparing Object types
```typescript
if (myInstance instanceof MyClass) {
    // type narrowed to 'MyClass'
}
```

### User-defined
Use these when comparing user defined interfaces
```typescript
function isFish(pet: Fish | Bird): pet is Fish {
    return (<Fish>pet).swim !== undefined;
}

// Both calls to 'swim' and 'fly' are now okay.

if (isFish(pet)) {
    pet.swim();
}
else {
    pet.fly();
}
```

## String Literal Types
Specify the exact value a string must have.
```typescript
type Easing = "ease-in" | "ease-out" | "ease-in-out";
class UIElement {
    animate(dx: number, dy: number, easing: Easing) {
        if (easing === "ease-in") {
            // ...
        }
        else if (easing === "ease-out") {
        }
        else if (easing === "ease-in-out") {
        }
        else {
            // error! should not pass null or undefined.
        }
    }
}
```

## Discriminated Unions
TODO

## 

以上是关于markdown 打字稿Cheatsheet的主要内容,如果未能解决你的问题,请参考以下文章

typescript 打字稿cheatsheet

markdown 打字稿界面类型

markdown withRouter打字稿

markdown 阿波罗查询打字稿

markdown 打字稿tsx

markdown 开玩笑,打字稿