Last active
May 16, 2023 03:17
-
-
Save pzi/48749342118861b0eb03ca036e23e6db to your computer and use it in GitHub Desktop.
Create a type-safe object based on an interface in TypeScript
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
// TS Playground: https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgDIHsDmoBi6oC2OwEANgCYDOyA3gFDLICul0IcBEAXMpWFKEwNkABziVKAd3zkA-Dz4CQmANx0AvnTpgAniJR5CxMlQA8AFQB8yALy1hAaigQ45dCFI7kAbQDWEL1Bkfx10GGRzAF0AWnlggI0tGCYQBDBgd2ZWYwoAOQ4ISgtLAAoASh5DIhIKIqt7RmcwJigQZBAISWQABSh0AA8dEpp1ZHFkKpyzKwAaBsZkTAgwEoB9OZE+-ShdMvmF5CaWts30bd1hRk0rssS6BHc+ZBga8nzOajsWCCn3wtMMNgQJNXpRSrcDsgAPRQ5AAPVkSVef0oADpvq0CpdIYwYfDES8TCjUWIJNIoORsTi8Qi6IS8gU0aSyTIqZCaYj7o90KQIKjSFgSvS3oz0axMZxbnQ8QBZOAifTkCJ6FAy9DkYCEqCULjS2EACzAYBEOphknNqNCTGaACM+Q8CFDJHAwAh9bIAG42AAMAC9MAB1dCrTAgX0ANQAkkA | |
interface LoginFormFields { | |
username: string | |
password?: string; | |
} | |
type FormFields<T> = { | |
// Mapped Type Modifiers: | |
// https://www.youtube.com/watch?v=0zgWo_gnzVI | |
+readonly [key in keyof T]-?: key | |
} | |
function useFieldNames<T>(): FormFields<T> { | |
return new Proxy({} as FormFields<T>, { | |
get(_, property) { | |
return property | |
} | |
}) | |
} | |
const fieldNames = useFieldNames<LoginFormFields>() | |
// ^? | |
fieldNames.username | |
// ^? | |
fieldNames.password | |
// ^? | |
fieldNames.passsword | |
// ^? | |
console.log(fieldNames.username) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment