How to initialize an object in TypeScript
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()
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> = {};