A few handy TypeScript types.
-
ThenType<T>
: When T
is a promise, resolves to the type the promise will resolve to (Promise<infer U>
). Otherwise, resolves to T
. Useful when you may or may not have a promise and need to reference the underlying type.
const value = 'foo';
const promise = Promise.resolve(value);
type V = ThenType<typeof value>;
type P = ThenType<typeof promise>;
-
FirstArgument<T>
: Resolves to the type of the first argument to the passed function. Useful for cases where you wish to extract the type of arguments without actually exporting the argument types, and is a nice complement to TypeScript’s built-in ReturnType
.
const func = (foo: Promise<any>) => foo.then(() => 'bar');
type Arg = FirstArgument<typeof func>;
-
ArrayElement<T>
: When T
is an array, resolves to the type contained within the array.
type FooArray = (string | number)[];
type Foo = ArrayElement<FooArray>;
-
Omit<T, K extends keyof T>
: The opposite of TypeScript’s Pick
type. Resolves to a new type that includes all keys in the original except those matching K
.
interface Obj {
foo: string;
bar: boolean;
baz: number;
}
type SelectiveObj = Omit<Obj, 'foo' | 'bar'>;
-
Props<T>
: Extracts the prop type from a React component. This allows you to access property types without having to manually export/ import the type.
function MyComponent({name}: {name: string}) {
return <div>Hello, {name}!</div>;
}
class MyOtherComponent extends React.Component<{seconds: number}> {
render() {
return <div>{this.props.seconds} seconds left!</div>;
}
}
type MyComponentProps = Props<typeof MyComponent>;
type MyOtherComponentProps = Props<typeof MyOtherComponent>;
-
DeepPartial<T>
: Recusively maps over all properties in a type and transforms them to be optional. Useful when you need to make optional all of the properties (and nested properties) of an existing type.
interface Obj {
foo: string;
bar: {
baz: boolean;
};
}
type DeepPartialObj = DeepPartial<Obj>;