Home

Enforcing Key-Values In TypeScript

An example of how to enforce certain allowed keys.

type Property = 'FontWeight' | 'TextColor' type AllowedPropPrefix = 'heading' | 'byline' | 'description' type AllowedPropName = `${AllowedPropPrefix}${Property}` type AllowedFontFamilyPropName = `${AllowedPropPrefix}FontFamily` type FontFamily = "body" | "heading" | "sans"; type ButtonVariant = "link" | "outline" | "ghost" | "solid" | "unstyled"; type AllowedEditableValue = FontFamily | ButtonVariant type EditableProps = Partial<{ [key in AllowedPropName]: AllowedEditableValue }> type EditableFontFamily = Partial<{[key in AllowedFontFamilyPropName]: FontFamily}> interface IComponent extends EditableProps, EditableFontFamily { name: string } const obj: IComponent = { name: 'test', headingFontFamily: 'heading', }

Repository

https://github.com/okeeffed/developer-notes-nextjs/content/typescript/enforcing-prop-names

Sections


Related