Utility Types

TypeScript utilities for safer DocLayer development

Last but not least, here is a collection of TypeScript utility types that enhance type safety and improve the developer experience across the application. These types help us with common type manipulations, transformations, and validations that frequently arise during development. So we think that you might find them useful as well.

Global Context

All of these types are globally exposed and easily accessible within the application context. However, when building side tooling - such as utilities or any other functions within the runtime - you may need to import them. In that cases, you can use named, destructured imports from @vuehouse/dl/types.

Bellow you'll find a comprehensive list of these types with brief descriptions of their functionality. Where applicable, with examples that illustrate how to use each effectively.


ArrayToString

Concatenates an array of strings into a single string.

Example:

type T1 = ArrayToString<['a', 'b', 'c']>;// results in: "a b c"type T2 = ArrayToString<['foo', 'bar', 'baz'], ','>; // or ', '// results in: "foo,bar,baz"type T3 = ArrayToString<[]>;// results in: ""
declare type ArrayToString<T extends readonly string[], Divider extends string = ' '> = T extends []  ? ''  : T extends [infer First extends string]    ? First    : T extends [infer First extends string, ...infer R extends string[]]      ? `${First}${Divider}${ArrayToString<R, Divider>}`      : string;

Type assists with inferring Tailwind class sets. We use it inside the utilTWC utility to convert class arrays defined within defineDoclayerComponentUi into a final string of classes. Additionally, it supports a custom divider, allowing you to separate the resulting strings with any character you choose.


DeepPartial

Deeply makes all properties in a given object possible undefined.

Example:

type Config = {  theme: {    colors: string[];    size: number;  };  layout: string;};type PartialConfig = DeepPartial<Config>;// results in: { theme?: { colors?: string[]; size?: number }; layout?: string; }
declare type DeepPartial<T> = {  [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K];};

This typ inverse of Required but applies recursively, making all nested properties optional. It might be useful when you need to define partial updates or optional configuration that matches the structure of a deeply nested object.


ExtractDelimiterString

Extracts the substring before or after a specified delimiter.

Example:

type Foo = ExtractDelimiterString<'hello-world', '-', 'before'>;// results in: 'hello'type Bar = ExtractDelimiterString<'abc_def', '_', 'after'>;// results in: 'def'type Baz = ExtractDelimiterString<'xyz', '_', 'after'>;// results in: 'xyz'
declare type ExtractDelimiterString<  T extends string,  Delimiter extends string = '-',  Side extends 'before' | 'after' = 'before',> = T extends `${infer Prefix}${Delimiter}${infer Suffix}` ? (Side extends 'before' ? Prefix : Suffix) : T;

Type lets you extract part of a string literal before or after a specific delimiter, useful for generating types like slug parts, extracting keys, or modifying naming schemes based on conventions. If the delimiter is not present, it just returns the original input.

It enables type-level string manipulation directly in your type definitions, for smarter mapped types and autocomplete.


Exact

Exact type match between two types A and B.

Example:

type User = { id: string; name: string };type UserWithEmail = { id: string; name: string; email: string };function getUser<T>(user: Exact<T, User>) {  console.log(user);}getUser<User>({ id: '1', name: 'Jane' }); // ✓ WorksgetUser<UserWithEmail>({ id: '1', name: 'Jane', email: 'j@example.com' }); // ✗ Type error
declare type Exact<A, B> = A extends B ? (B extends A ? A : never) : never;

Type ensures that two types match exactly, not allowing extensions or variations. It can be useful for enforcing strict type equality in generic functions and avoiding accidental type widening.

It's a popular implementation of the very anticipated Exact utility type.


KeyPartial

Makes specific keys in an object optional or required based on a condition.

Example:

type User = { id: string; name: string; email: string };// Make only 'email' optionaltype UserWithoutEmail = KeyPartial<User, 'email', true>;// Result: { id: string; name: string; email?: string; }// Make 'email' and 'name' requiredtype RequiredUser = KeyPartial<User, 'email' | 'name', false>;// Result: { id: string; name: string; email: string }
declare type KeyPartial<  T extends object,  Keys extends keyof T,  IsOptional extends boolean,  ConditionRef extends boolean = true,> = Omit<T, Keys> & ([IsOptional] extends [ConditionRef] ? { [P in Keys]?: T[P] } : { [P in Keys]-?: T[P] });

Type that can help in creating variations of existing types with different combinations of required and optional properties. It enables you to selectively make specific keys optional or required within an object type, giving you precise control over property requirements. For example, we use it to distinguish the in-module app.config.ts (where some options are required) from the user-defined config (where all options can be optional).


LooseAutocomplete

Loose autocomplete for string literals, allowing both the specified strings and custom ones.

Example:

type Theme = 'light' | 'dark' | 'auto';type LooseTheme = LooseAutocomplete<Theme>;// Allows both predefined values and any other stringfunction setTheme(theme: LooseTheme) {  // ...}setTheme('light'); // ✓ WorkssetTheme('dark'); // ✓ WorkssetTheme('custom-theme'); // ✓ Also works
declare type LooseAutocomplete<T extends string> = T | (string & {});

Type provides IntelliSense autocomplete for specific string literals while still allowing any other string to be passed. The & {} trick preserves autocomplete suggestions in IDEs while keeping the type open.

DeepNonNullable

Deeply makes all properties in a given object non-nullable.

Example:

type User = {  id: string | undefined | null;  profile?: {    email?: string | null;    name?: string;  } | null;};type NonNullUser = DeepNonNullable<User>;// results in: all properties required and non-nullable
declare type DeepNonNullable<T> = T extends Function  ? T  : T extends object    ? { [K in keyof T]-?: DeepNonNullable<NonNullable<T[K]>> }    : NonNullable<T>;

Type can be helpful when you need to ensure that all properties in a nested object structure are required and non-null, converting optional nullable properties into required ones at every level of the object hierarchy.


Prettify

Flattens objects allowing them to be fully inferred and displayed.

Example:

type Nested = {  a: { b: { c: number } };};type Prettified = Prettify<Nested>;// results in: a readable, expanded structure instead of nested intersection
declare type Prettify<T> = T extends Primitive  ? T  : {      [K in keyof T]: T[K];    } & {};

Type flattens complex type structures for better readability in TypeScript errors and IDE displays. It can be particularly useful for debugging complex type compositions.


RequireConst

Requires a tuple type, creating an as const equivalent at the type level.

Example:

type StringArray = string[];type StringTuple = [string, string];type RequiredConst1 = RequireConst<StringArray>; // results in: nevertype RequiredConst2 = RequireConst<StringTuple>; // results in: [string, string]// Enforce tuple usagefunction processItems<const T extends readonly any[]>(items: RequireConst<T>): T {  return items;}// ✓ works with tuplesprocessItems(['a', 'b', 'c'] as const);// ✗ type error with arraysprocessItems(['a', 'b', 'c']);
type IsTuple<T extends readonly any[]> = T['length'] extends number ? false : true;declare type RequireConst<T extends readonly any[]> = IsTuple<T> extends true ? T : never;

Type enforces that only tuple types can be used, rejecting regular arrays. Useful when you need to ensure specific array shapes at compile time, working similarly to the as const assertion but at the type level. Thank's to the type you don't need to use as const anymore in those cases.


ReverseUndefined

Removes undefined from a given object keys.

Example:

type Config = {  theme?: string | undefined;  layout: string | undefined;  size: string;};type Reversed = ReverseUndefined<Config>;// results in: { theme: string; layout: string; size: string; }
declare type ReverseUndefined<T> = {  [K in keyof T]-?: undefined extends T[K] ? Exclude<T[K], undefined> : T[K];};

Type removes undefined from all properties in an object type, making all properties required and non-undefined, even if they were originally optional or could be undefined.