Created
January 25, 2024 15:36
-
-
Save insytes/7af034cfcd3d7e065ee0fb92034dc938 to your computer and use it in GitHub Desktop.
Typescript options object helper
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
// 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