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?
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", };
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 ( {} ).
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.
There are a number of ways to solve this problem, depending on your desired result.
interface
to a class
export class Category { name: string; description: string; } const category: Category = new Category();
interface
as a class
export class CategoryObject implements Category { } const category: Category = new CategoryObject();
interface
const category: Category = { name: 'My Category', description: 'My Description', };
export interface Category { name?: string; description?: string; } const category: Category = {};
Partial<T>
export interface Category { name: string; description: string; } const category: Partial<Category> = {};
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With