Skip to content

Instantly share code, notes, and snippets.

@ardyfeb
Last active March 25, 2022 08:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ardyfeb/ad19183ef6605512d898cbe3f097094d to your computer and use it in GitHub Desktop.
Save ardyfeb/ad19183ef6605512d898cbe3f097094d to your computer and use it in GitHub Desktop.

Advanded Typescript Generic

Use and play with Typescript Generic like a pro.

Table of Contents:

  1. Conditional Types
  2. String Concatenate
  3. infer Keyword
  4. Type Assertion

Conditional Types

Logical types baseed on given generic

Syntax

type NoNull<T> = T extends null ? never : T

Use Case

To build complex logical types

Usage

interface Exception {
  kind: {
    stack: number
    message: string
  }
}

type Payload<T extends Exception | string>  = {
  body: T extends Exception ? Exception["kind"] : string
}

String Concatenate

We can concat the given generic just with Javascript String Literal Syntax

Syntax

type FullName<F extends string, S extends string> = `${F} ${L}`

Use Case

  • Type static string

infer Keyword

A keyword to extract unknown type and assign to generic

Use Case

type Unpromisify<T> = T extends Promise<infer R> ? R : T

Type Assertion

Example

interface Plane {
    fly: () => void
}

interface Car {
    run: () => void
}
function canFly(entity: Plane | Car): entity is Plane {
    return !!(entity as Plane).fly
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment