Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an object in TypeScript

Tags:

typescript

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?

like image 957
Aragorn Avatar asked Oct 02 '18 20:10

Aragorn


People also ask

How do you initialize an object in TypeScript?

To initialize an object in TypeScript, we can create an object that matches the properties and types specified in the interface. export interface Category { name: string; description: string; } const category: Category = { name: "My Category", description: "My Description", };

How do you initialize an object?

Objects can be initialized using new Object() , Object. create() , or using the literal notation (initializer notation). An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ( {} ).

How do you initialize a number in TypeScript?

The type syntax for declaring a variable in TypeScript is to include a colon (:) after the variable name, followed by its type. Just as in JavaScript, we use the var keyword to declare a variable. Declare its type and value in one statement.


2 Answers

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> = {}; 
like image 158
Ian MacDonald Avatar answered Oct 14 '22 07:10

Ian MacDonald


If you don't want to change your definition from interface to class, you could also do:

let category = <Category>{ }; 

Otherwise, you could follow other answers and change your Category to be a class.

edit: as per ruffin's comment below, if the interface is

export interface ITiered { one: { two: { three: function (x) {...} } } }  

and you try let x = {} as ITiered, then you'll have an error when you call something like x.one.two.three()

like image 35
Vitor M. Barbosa Avatar answered Oct 14 '22 07:10

Vitor M. Barbosa