Skip to content

Instantly share code, notes, and snippets.

@jdfm
Last active June 17, 2019 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdfm/cc795fa760d37289c2e194a45f5f7368 to your computer and use it in GitHub Desktop.
Save jdfm/cc795fa760d37289c2e194a45f5f7368 to your computer and use it in GitHub Desktop.
Typescript: Typing Destructured Arguments
/**
* Typing destructured arguments
*/
/**
* You don't need to know the type of the destructured prop up front with this construct.
* Useful for cases where you want to make a function that destructures something and passes that value along.
* No intellisense.
*/
export type PassthroughProperty<K extends PropertyKey> = <T extends Pick<any, K>>(arg: T) => T[K]
const passthroughTest: PassthroughProperty<'data'> = ({ data }) => data
/**
* [1]: Seen as
* const passthroughTest: <{
* data: number;
* something: string;
* }>(arg: {
* data: number;
* something: string;
* }) => number
*
* [2]: Complains if you don't have the 'data' property in the object you're passing.
*/
passthroughTest({ data: 1, something: 'else' }) // [1] [2]
/**
* You need to know your types up front with this construct.
* Allows for full separation of your function declarations and their definitions if you need it.
* Can fully specify all arguments and the return type.
* Since you've typed the arguments, intellisense is available.
*/
export type Lambda<A extends any[], R> = (...args: A) => R
export type Arbitrary<T> = {
[key: string]: any
} & T
type PassthroughData = Lambda<[Arbitrary<{ data: number }>], number>
const lambdaTest: PassthroughData = ({ data }) => data
/**
* [1]: Seen as
* const lambdaTest: (args_0: Arbitrary<{
* data: number;
* }>) => number
*
* [2]: Complains if you don't have the 'data' property in the object you're passing.
*/
lambdaTest({ data: 1, something: 'else' }) // [1] [2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment