Skip to content

Instantly share code, notes, and snippets.

@bsitruk
Created June 14, 2022 09:58
Show Gist options
  • Save bsitruk/70b56b0e515e0f34ceb2b2d22c89266a to your computer and use it in GitHub Desktop.
Save bsitruk/70b56b0e515e0f34ceb2b2d22c89266a to your computer and use it in GitHub Desktop.
Constrained Identity Function
- Use Case: We want to create a Record with a limited set of Keys, and a defined type of Values.
- We also don't want to Type the Set of Keys, but leverage TypeScript inference instead (DRY)
- If we create a new inline object literal, TypeScript will prevent any new key from being added, by won't enforce the type of the Values.
- So Narrow Keys, Wide Value Type
- If we specify the type Record<string, number>, we'll be able to add any new Key after the object creation
- So Wide Keys, Narrow Value Type
- By using a Types Identity Function, we can build an object with enforced Value Type, and Narrow set of Keys.
```
const createObject = <ObjectType extends Records<string, number>> (item: ObjectType) => item
const object = createObject({ x: 1, y: 2, z: "3" // Type Error })
object.w = 5 // Error, key doesn't exist
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment