Skip to content

Instantly share code, notes, and snippets.

@treecy
Last active July 8, 2020 00:13
Show Gist options
  • Save treecy/ba497b8338cd239b927232806ab74148 to your computer and use it in GitHub Desktop.
Save treecy/ba497b8338cd239b927232806ab74148 to your computer and use it in GitHub Desktop.
[Typescript Use Case] Typescript use case collection
/**
* A function returns a object, the key of the object is the value of the input object
* Declare the type for the following fuction
* e.g. const mappingFunc = obj => ({[obj.name]: true})
**/
const mappingFunc = <T extends string>(arg: {name: T}): Record<T, boolean> => ({
[arg.name]: true
})
const obj = {
name: 'foo' as 'foo' // <-- narrow down the type from `string` to `"foo"` (String Literal Type)
}
const output = mappingFunc<typeof obj.name>(obj);
console.log(output.foo) // true
console.log(output.bar) // error: TS2339: Property 'bar' does not exist on type 'Record<"foo", boolean>'.
/* Variadic Tuple Types (generic tuple with spread) */
function tail<T extends any[]>(arr: readonly [any, ...T]) {
const [_ignored, ...rest] = arr;
return rest;
}
const myTuple = [1, 2, 3, 4] as const;
const myArray = ["hello", "world"];
// type [2, 3, 4]
const r1 = tail(myTuple);
// type [2, 3, ...string[]]
const r2 = tail([...myTuple, ...myArray] as const);
// well-typed signature for concat:
type Arr = readonly any[];
function concat<T extends Arr, U extends Arr>(arr1: T, arr2: U): [...T, ...U] {
return [...arr1, ...arr2];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment