A comprehensive collection of useful TypeScript generic types to enhance your type-safety and development experience.
npm install typescript-generic-types
# or
yarn add typescript-generic-types
Simply import the package at the top of any file in your project:
import 'typescript-generic-types'
Represents a value that could be either a single item or an array of items.
type Example = MaybeArray<string>; // string | string[]
Represents a value that could be either the direct type or a Promise of that type.
type Example = MaybePromise<number>; // number | Promise<number>
A type-safe way to represent any function.
const myFunc: FunctionGeneric = (...args) => console.log(args);
Represents any object with string keys and any values.
const obj: ObjectGeneric = { key: 'value' };
Check if the object type has some keys. Return 'false' if there is no keys
Ensures a type is not a function.
Makes all properties of an object (and its nested objects) optional.
Giving a list of required fields and subfields (dot notation) this type will return the object with the required fields added to type
type Obj = {
a: string;
aOptional?: string;
b: {
c?: string
d?: string
e: string
}
}
type RequiredFields = {
aOptional: true
'b.c': true
}
type Result = AddRequiredFieldsToObject<Obj, RequiredFields>
// PARSED TYPE:
type Result = {
a: string
aOptional: string // this has became required because we specified it in RequiredFields
b: {
c: string // ALSO did this field
d?: string // this one has kept being optional
e: string // " " " " required
}
}
type Example1 = RemoveFirst<[boolean, number, string]>; // [number, string]
type Example2 = RemoveFirst<[boolean, string]>; // [string]
type Example3 = RemoveFirst<[boolean]>; // []
type Example4 = RemoveFirst<[]>; // never
Creates mutually exclusive property sets.
type Example = Exclusive<{propA: string}, {propB: number}>;
// Either has propA or propB, but not both
Forces a type to conform to another type if possible.
Makes all properties of an object required and non-nullable.
Combines two types, with T2 properties overriding T1 properties.
Represents ISO country codes (two letters).
const country: CountryCodeIso = 'us'; // valid
const invalid: CountryCodeIso = 'usa'; // error
Ensures an array has at least one element.
Gets the keys (indices) of an array as a type.
Ensures an object only contains defined properties.
Removes properties of a specific type from an object.
Ensures all object keys are strings.
Makes an object and all its nested properties readonly.
Type representing days of the week (0-6).
Type for common environment names.
const env: Env = 'production'; // Valid values: 'test' | 'development' | 'production' | 'preprod' | 'build' | 'ci'
Contributions are welcome! Please feel free to submit a Pull Request.
MIT