Skip to content

Instantly share code, notes, and snippets.

@insytes
Created January 25, 2024 15:36
Show Gist options
  • Save insytes/7af034cfcd3d7e065ee0fb92034dc938 to your computer and use it in GitHub Desktop.
Save insytes/7af034cfcd3d7e065ee0fb92034dc938 to your computer and use it in GitHub Desktop.
Typescript options object helper
// helper type
type RequiredProps<T, K extends keyof T> = Partial<T> & Required<Pick<T, K>>
type Person = {
id: string
name: string
formatted_name: string
age: number
}
function createPerson(person: RequiredProps<Person, "name" | "age">): Person {
return {
id: person.id || "1",
name: person.name,
age: person.age,
formatted_name: person.formatted_name || "The one and only " + person.name,
}
}
console.log(createPerson({ name: "Dave", age: 33 }));
console.log(createPerson({ name: "Dave", age: 33, formatted_name: "Master Dave" }));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment