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:
type TextType = "Text"; // or "Message" if format changes later
type TitleType = "Title";
type PriorityType = "Priority";
type Notification = Partial<Record<typeof TextType | typeof TitleType, string>
& Record<typeof PriorityType, number>>;
let notif: Notification;
let t = notif[TextType] // Will be string
let 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" etc
const TitleType = "Title";
const PriorityType = "Priority";
interface Notification {
[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"