Last active
June 17, 2019 14:36
-
-
Save jdfm/cc795fa760d37289c2e194a45f5f7368 to your computer and use it in GitHub Desktop.
Typescript: Typing Destructured Arguments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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