Home > Mobile >  Use a reserved keyword as a property in a typescript interface
Use a reserved keyword as a property in a typescript interface

Time:05-09

I’d like to define a typescript interface to map answers from a web service to a type (similar to what is shown here). Here is an example answer.

{
    "type": "Seen",
    "creation": 33,
    "fileId": 6
}

Hence the following interface would be suitable.

interface Event {
    type: 'Accepted' | 'Judgment' | 'Seen';
    creation: number;
    fileId: number;
}

Unfortunately, the compiler does not like it: type is a reserved keyword.

How can I use a reserved keyword as a property inside an interface?

I guess it is possible to define the property using another term and then define an alias to it somehow, as suggested here, or use var instead as suggested here, but I can’t find out how to do it in my case.

CodePudding user response:

It is perfectly fine to use properties called type in an interface. In fact, you can use all keywords of TypeScript in interfaces:

interface Test {
  type: string
  class: string
  any: string
}

The problem here is that you are modifying an existing interface which already defines type to be of type string:

// lib.dom.d.ts
/** An event which takes place in the DOM. */
interface Event {
  readonly type: string;
  /* ... */
}

You can define multiple interfaces with the same name to merge them. This is called "Declaration Merging". But if you define the same properties with different types you get the following error:

All declarations of 'type' must have identical modifiers.


So unless you are trying to modify the globally available interface Event, you should just choose another name of the interface.

  • Related