Last active
March 29, 2021 10:47
-
-
Save misha-erm/fbdabffef0fdb5a12ae2ca17bdc57969 to your computer and use it in GitHub Desktop.
[Typescript] - Constrained identity function
This file contains hidden or 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
/** | |
* Problem: defining object with interfaces grant autocomplete but also widen all types (e.g. `true` becomes `boolean`) | |
* Defining object with `as const` infers all the narrowed types but looses autocomplete | |
* Solution: Create utility function with constrained generic type parameters. More info [here](https://kentcdodds.com/blog/how-to-write-a-constrained-identity-function-in-typescript) | |
*/ | |
interface ISchema { | |
id: string; | |
description: string; | |
bool: boolean; | |
} | |
const createSchema = <T extends ISchema>(schema: Readonly<T>) => schema; | |
const schema = createSchema({ | |
id: "qwer", | |
description: "description", | |
bool: true, | |
}); | |
schema.id // 'qwer' | |
schema.bool // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment