Use and play with Typescript Generic like a pro.
- Conditional Types
- String Concatenate
- infer Keyword
- Type Assertion
Logical types baseed on given generic
type NoNull<T> = T extends null ? never : T
To build complex logical types
interface Exception {
kind: {
stack: number
message: string
}
}
type Payload<T extends Exception | string> = {
body: T extends Exception ? Exception["kind"] : string
}
We can concat the given generic just with Javascript String Literal Syntax
type FullName<F extends string, S extends string> = `${F} ${L}`
- Type static string
A keyword to extract unknown type and assign to generic
type Unpromisify<T> = T extends Promise<infer R> ? R : T
interface Plane {
fly: () => void
}
interface Car {
run: () => void
}
function canFly(entity: Plane | Car): entity is Plane {
return !!(entity as Plane).fly
}