Warm tip: This article is reproduced from stackoverflow.com, please click
typescript

How to initialize an object in TypeScript

发布于 2020-04-03 23:36:47

I have a simple model class

export interface Category {

  name: string;
  description: string;

}

I need to declare and initialize a variable in an angular component. Tried:

category: Category = {};

Error: {} is not assignable to a Category

category: Category = new Category();

error: Category refers to a type, but being referred as value..

Any suggestions?

Questioner
Aragorn
Viewed
16
Ian MacDonald 2020-03-10 23:38

There are a number of ways to solve this problem, depending on your desired result.

Way 1: Convert your interface to a class

export class Category {
  name: string;
  description: string;
}
const category: Category = new Category();

Way 2: Extend your interface as a class

export class CategoryObject implements Category {
}
const category: Category = new CategoryObject();

Way 3: Fully specify your object, matching the interface

const category: Category = {
  name: 'My Category',
  description: 'My Description',
};

Way 4: Make the properties optional

export interface Category {
  name?: string;
  description?: string;
}

const category: Category = {};

Way 5: Change your variable's type to use Partial<T>

export interface Category {
  name: string;
  description: string;
}

const category: Partial<Category> = {};