addons/shared/typeUtils.tsblame
View source
b69ab311/**
b69ab312 * Copyright (c) Meta Platforms, Inc. and affiliates.
b69ab313 *
b69ab314 * This source code is licensed under the MIT license found in the
b69ab315 * LICENSE file in the root directory of this source tree.
b69ab316 */
b69ab317
b69ab318/**
b69ab319 * Remove particular keys from an object type:
b69ab3110 * ```
b69ab3111 * Without<{foo: string, bar: string, baz: number}, 'bar' | 'baz'> => {foo: string}
b69ab3112 * ```
b69ab3113 */
b69ab3114export type Without<T, U> = {[P in Exclude<keyof T, keyof U>]?: never};
b69ab3115
b69ab3116/**
b69ab3117 * Given two object types, return a type allowing keys from either one but not both
b69ab3118 * ```
b69ab3119 * ExclusiveOr({foo: string}, {bar: number}) -> allows {foo: 'a'}, {bar: 1}, but not {foo: 'a', bar: 1} or {}
b69ab3120 * ```
b69ab3121 */
b69ab3122export type ExclusiveOr<T, U> = T | U extends object
b69ab3123 ? (Without<T, U> & U) | (Without<U, T> & T)
b69ab3124 : T | U;
b69ab3125
b69ab3126/**
b69ab3127 * Make every key of a type optional, and make its type undefined
b69ab3128 * ```
b69ab3129 * AllUndefined<{foo: string}> => {foo?: undefined}
b69ab3130 * ```
b69ab3131 */
b69ab3132export type AllUndefined<T> = {[P in keyof T]?: undefined};
b69ab3133
b69ab3134/**
b69ab3135 * Make every key of the object NOT readonly. The opposite of Readonly<T>.
b69ab3136 * ```
b69ab3137 * {readonly foo: string} -> {foo: string}
b69ab3138 * ```
b69ab3139 */
b69ab3140export type Writable<T> = {-readonly [P in keyof T]: T[P]};
b69ab3141
b69ab3142export type Json = string | number | boolean | null | Json[] | {[key: string]: Json};
b69ab3143
b69ab3144type UnionKeys<T> = T extends unknown ? keyof T : never;
b69ab3145type StrictUnionHelper<T, TAll> = T extends unknown
b69ab3146 ? T & Partial<Record<Exclude<UnionKeys<TAll>, keyof T>, undefined>>
b69ab3147 : never;
b69ab3148/**
b69ab3149 * Make a union type T be a strict union by making all keys required.
b69ab3150 * This allows a discriminated union to have fields accessed without a cast.
b69ab3151 * For example,
b69ab3152 * ```
b69ab3153 * StrictUnion<{type: 'foo', foo: string} | {type: 'bar', bar: number}> => {type: 'foo' | 'bar', foo?: string, bar?: number}
b69ab3154 * ```
b69ab3155 */
b69ab3156export type StrictUnion<T> = StrictUnionHelper<T, T>;
b69ab3157
b69ab3158/**
b69ab3159 * Construct a type with the properties of T except for those in type K,
b69ab3160 * applicable to T being a union type.
b69ab3161 * ```
b69ab3162 * UnionOmit<foo | bar, 'baz'> => Omit<foo, 'baz'> | Omit<bar, 'baz'>
b69ab3163 * ```
b69ab3164 */
b69ab3165export type UnionOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;