Created
June 14, 2022 09:58
-
-
Save bsitruk/70b56b0e515e0f34ceb2b2d22c89266a to your computer and use it in GitHub Desktop.
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
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