/typescript-notes

Personal notes & references for typscript related things

Primary LanguageTypeScript

My Random TS Stuff

Misc

known-keys

typescript-remove-index-signature-using-mapped-types-remove-index-signature-using-mapped-types

export type KnownKeys<T> = {
  [K in keyof T]: string extends K ? never : number extends K ? never : K
} extends { [_ in keyof T]: infer U } ? U : never;

interface Options {
  key: string;
  title: string;
  [dataProperty: string]: string | number;
}
type KnownKeysOfOptions = KnownKeys<Options>; // 'key' | 'title';
// (vs. type KeysOfOptions = keyof Options // string | number;)

Cast

Type cast an argument. If no type is provided it will default to any

export const Cast = <T = any>(arg: any): T => arg;

Overloading a private function

Example on overloading private functions

export function someFunction(arg1: string, arg2 = false) {
  return someFunction;

  function someFunction(arg3: undefined): undefined;
  function someFunction(arg3: string | number): string;
  function someFunction(arg3: string | number | undefined) {
    return typeof arg3 == "undefined"
      ? undefined
      : (arg2 && !Number.isNaN(Number(arg3))) || typeof arg3 == "number"
      ? arg1 + "something"
      : arg3;
  }
}

References

Collections

  • dzharii/awesome-typescript A collection of awesome TypeScript resources for client-side and server-side development. Write your awesome JavaScript in TypeScript

Articles/Discussions

Releases

Conditionals

React Related

Functional

Tracking Issue

Gerneral Utility Types

React Related Utility Types

  • rex-tils - Type safe utils for redux actions, epics, effects, react/preact default props, various type guards and TypeScript utils, React util components

Typescript Function Utilities

Mix of Functions & Types

CSS Related

  • mocoolka-css - Mocoolka-css define Css Component with orginal css property and predefine property.
  • csx - Utility functions for TypeStyle
  • csstype - Strict TypeScript and Flow types for style based on MDN data
  • @johanneslumpe/css-types -TypeScript CSS types and value helpers generated from MDN data

Misc

  • uom-ts - Units of measure type safety, with no runtime overhead, supporting multiplication and division

Issues

Issues with WorkArounds

WorkAround:

type LiteralUnion<T extends U, U = string> = T | (U & { zz_IGNORE_ME?: never })

Example:

type Color = LiteralUnion<'red' | 'black'>

var c: Color = 'red'                    // Has intellisense
var d: Color = 'any-string'             // Any string is OK
var d: Color = { zz_IGNORE_ME: '' }     // { zz_IGNORE_ME } placeholder is at the bottom of intellisense list and errors because of never 

type N = LiteralUnion<1 | 2, number> // Works with numbers too