Skip to content Skip to sidebar Skip to footer

Typescript Interface, Using String Constants For Properties

I recently encountered the following design-issue when trying to describe a Notification-format (and formats in general) with a Typescript interface. Context: Notifications are exc

Solution 1:

You can use the Record<TKey, TValue> type to define the interface:

typeTextType = "Text"; // or "Message" if format changes latertypeTitleType = "Title";
typePriorityType = "Priority";
typeNotification = Partial<Record<typeofTextType | typeofTitleType, string>
        & Record<typeofPriorityType, number>>;

letnotif: Notification;

let t = notif[TextType] // Will be stringlet t2 = notif.Text// Also works 

The problem is there is no compiler way to enforce that access happens using the string constant, you could still access with .

Note

On typescript 2.7 and newer you can also do:

const TextType = "Text"; // or "Message" etcconst TitleType = "Title";
const PriorityType = "Priority";

interfaceNotification {
    [TextType]?: string
    [TitleType]?: string
    [PriorityType]?: number
}

But the same problem still applies of access

Post a Comment for "Typescript Interface, Using String Constants For Properties"