UTILITY_TYPES - sajiro/ts-love GitHub Wiki

EXTRACT

type Trip =
  | {
      origin: {
        uuid: string;
        city: string;
      };
    }
  | { originUuid: string };

// get a type from a discriminated type
type TripWithOriginRef = Extract<Trip, { originUuid: string }>;
type TripWithOriginWhole = Extract<Trip, { origin: { uuid: string } }>;

const tripWithOriginRef = { originUuid: "123" };

const tripWithOriginWhole = {
  origin: {
    uuid: "string",
    city: "string",
  },
};
const hasOriginRef = (trip: Trip): trip is TripWithOriginRef => {
  return "originUuid" in trip;
};

const isDraft = (trip: Trip): trip is TripWithOriginWhole => {
  return "origin" in trip;
};

// get the TripWithOriginRef using filter
const result = [tripWithOriginRef, tripWithOriginWhole].filter(hasOriginRef);
console.log(result);

console.log(isDraft(tripWithOriginWhole))

// hover result so you will see the importance
/* type of the result should be 
const result: {
  originUuid: string;
}[] 
because we are filtering 
*/

type Diesel = {
  type: "petroleum" | "bio" | "synthetic";
};

type Gasoline = {
  type: "hybrid" | "conventional";
};

type Bus = {
  engine: Diesel;
};

type Car = {
  engine: Gasoline;
};

type Engine<T> = T extends {engine:unknown } ? T["engine"] : never;
type BusEngine = Engine<Bus>

const busEngine : BusEngine = {
  type:"bio"
}

const carEngine:Engine<Car> = {
  type:"bio" // should be error, 
}

OMIT

import {Button, ButtonProps} from "@material-ui/core"

type Props = Omit<ButtonProps, "variant">;
//if use ButtonProps directly in react FC it will get all the props of the material button
//Omit will remove the "variant" props
const BrandButton: React.FC<Props> = ({children, ...rest}) => {
  return <Button {...rest}>{children}</Button>
}

export default BrandButton
⚠️ **GitHub.com Fallback** ⚠️