Typescript & React: Manipulating Prop Types

How to use Extend and Pick helpers with generic types, intersection types, and more

Extending prop types

type CombinedProps = BaseProps & FormProps
type BaseProps = {
className?: string,
style?: React.CSSProperties
};

Intersection Types

ExtendedProps = {
isDisabled?: boolean,
isError?: boolean,
...
}
// combining two typestype FullProps = BaseProps & ExtendedProps;
// or attaching properties to a type
type FullProps = BaseProps & {
isDisabled?: boolean,
isError?: boolean,
...
}
// this is an error!ExtendedProps = {
className?: string,
isDisabled?: boolean,
isError?: boolean,
...
}
type FullProps = BaseProps & ExtendedProps;
// form handler type, expecting values[] and errors[]type FormHandlerProps = {
(values: any[], errors?: string[]) => void
}
type FullProps = BaseProps & ExtendedProps & FormHandlerProps

A note on union types

type FormElementProps = TextareaProps | DropdownProps;
// getValue can support a key string or index, and can return empty resultsfunction getValue(key: string | number): string | null {     
...
}

Removing unneeded props

// a function for dropping a subset of propsfunction dropProps(obj) {
let { x, y, z, ...rest } = obj;
return rest;
}
// interface for props we will dropinterface APIMetaProps {
_id: number;
created: number;
last_updated: number;
}
// a generic type that drops unwanted metadata prop typestype DropAPIMeta<T> = Pick<T, Exclude<keyof T, keyof APIMetaProps>>
type User = {
_id: number;
created: number;
name: string;
};
type UserNoMeta = Exclude<User, '_id' | 'created'>
type UserNoMeta = Pick<User, 'name'>
type DropAPIMeta<T> = Pick<T, Exclude<keyof T, keyof APIMetaProps>>;
function dropAPIMeta<T extends DropAPIMeta>(obj: T): DropAPIMeta<T> {
let { _id, created, last_updated, ...rest } = obj;
return rest;
}
// interface for unneeded propsinterface APIMetaProps {
_id: number;
created: number;
last_updated: number;
}

//generic type for props - unneeded props
type DropAPIMeta<T> = Pick<T, Exclude<keyof T, keyof APIMetaProps>>;
//utility function to remove unneeded props from an object
function dropAPI<T extends DropAPIMeta>(obj: T): DropAPIMeta<T> {
let { _id, created, last_updated, ...rest } = obj;
return rest;
}

Removing Props in HOC Functions

function withoutAPIMeta<Props>(WrappedComponent: React.ComponentType<Props>) {
return class extends React.Component<Props> {

render() {
let { _id, created, last_updated, ...rest } = this.props;
return <WrappedComponent {...rest} />;
}
};
}

To Conclude

Programmer and Author. Director @ JKRBInvestments.com. Creator of LearnChineseGrammar.com for iOS and Android.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store