Built In Types

Named

Use ft.Named to add names to types for use in error messages. This is especially useful for large unions that can otherwise have very long error messages.

import * as ft from "funtypes";

const UserCodec = ft.Named(
  "User",
  ft.Object({
    type: ft.Literal("USER"),
    id: ft.Number,
    name: ft.String,
  }),
);

const PostCodec = ft.Named(
  "Post",
  ft.Object({
    type: ft.Literal("POST"),
    id: ft.Number,
    title: ft.String,
  }),
);

export const DbObjectCodec = ft.Union(
  UserCodec,
  PostCodec,
);
// => ft.Codec<{ type: "USER"; id: number; name: string } | { type: "POST"; id: number; title: string }>

export type DbObjectType = ft.Static<
  typeof DbObjectCodec
>;
// => { type: "USER"; id: number; name: string } | { type: "POST"; id: number; title: string }

// ✅ Instead of printing out the full type, it
//    just refers to sub-types by name
assert.deepEqual(
  ft.showType(DbObjectCodec),
  "User | Post",
);

Other than improving error messages, ft.Named should never make any difference to the behaviour of your funtypes.

Previous
Mutable
Next
Never