Kim Gentes Kim Gentes - 3 months ago 20
TypeScript Question

How Do I get a single instance of an interface in Typescript

I am trying to figure out how to get a single instance of an interface in Typescript. I have the following code that works:

export interface IOpenStatus {
filePath: string;
openSuccess: boolean;
error: string;
fileData: string;
}

openStatus: IOpenStatus[];


However, if I want just a single instance of the interface to be defined, this fails:

openStatus: IOpenStatus;


This fails as well:

let openStatus= new IOpenStatus();


It seems that the array "[]" is somehow substituting for an instance creation mechanism (albeit for multiple instances). In my situation, I never want to instantiate more than a single instance of the interface.

How do I instantiate a single instance of the interface? I am needing to use an interface because I am going to return this data from the server with this same interface.

UPDATE
I can see part of the problem was I didn't specify the context. I am doing this in an Angular2 application. In my situation, I was using

openStatus: IOpenStatus[];


as part of a class property definition (a component to be exact). It seems that the array notation does simply allow Javascript to anticipate the instantiation of an array of the type of the interface without any further definition (it can be used as an array of such, immediately thereafter).

What I have to do, in the end to utilize:

userOpenStatus = new OpenStatus();


is to implement the interface in a class such as :

export interface IOpenStatus {
filePath: string;
openSuccess: boolean;
error: string;
fileData: string;
}

export class OpenStatus implements IOpenStatus {
filePath: string;
openSuccess: boolean;
error: string;
fileData: string;
}

Answer

Given:

export interface IOpenStatus {
    filePath: string;
    openSuccess: boolean;
    error: string;
    fileData: string;
}

This, on its own, is a syntax error:

openStatus: IOpenStatus[];

(Though it would be valid as a class property declaration.) You might need something like:

let openStatus: IOpenStatus[];

This corresponds exactly to the plain JS version:

let openStatus;

The only difference is the type annotation. If you don't want it to be an array of your type, just say:

let openStatus: IOpenStatus;

In order to appear after the new keyword, an identifier must be the name of a constructor function, and the easiest way to declare one of those is with the class keyword. But you could just use a type literal:

openStatus = {
    filePath: "/blah",
    openSuccess: true,
    error: "",
    fileData: "Hello, world."
};

That has all the properties required for IOpenStatus, so it can be assigned to a variable of that type.