Skip to content

Instantly share code, notes, and snippets.

@misha-erm
Last active March 29, 2021 10:47
Show Gist options
  • Save misha-erm/fbdabffef0fdb5a12ae2ca17bdc57969 to your computer and use it in GitHub Desktop.
Save misha-erm/fbdabffef0fdb5a12ae2ca17bdc57969 to your computer and use it in GitHub Desktop.
[Typescript] - Constrained identity function
/**
* 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