Typescript - Record, Partial and defined object keys

Monday Apr 13, 2020

Let’s say we have a Typescript object that looks like this:

{ 
	profile: { 
		first: {x: 2, y: 3}, 
		second: {x: 4, y: 5} 
	} 
}
Now, we can define this as:

type Point = { x: number, y: number }

type Profile = {
	  first: Point,
	  second: Point
}

interface Profile {
	profile: Profile
}

Let’s say we want to define a list of properties that are valid for profile rather than hard-coding all that:

type ProfileField = "first" | "second"
	
interface Profile extends Record<ProfileField, Point>
	

Now, if we want to make the fields optional:

type ProfileField = "first" | "second"
	
interface Profile extends Partial<Record<ProfileField, Point>>