如何在 TypeScript 中初始化对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52616172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to initialize an object in TypeScript
提问by Aragorn
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?
有什么建议?
回答by Ian MacDonald
There are a number of ways to solve this problem, depending on your desired result.
有多种方法可以解决此问题,具体取决于您想要的结果。
Way 1: Convert your interface
to a class
方式 1:将您的转换interface
为class
export class Category {
name: string;
description: string;
}
const category: Category = new Category();
Way 2: Extend your interface
as a class
方式 2:扩展您的interface
身份class
export class CategoryObject implements Category {
}
const category: Category = new CategoryObject();
Way 3: Fully specify your object, matching the interface
方式3:完全指定您的对象,匹配 interface
const category: Category = {
name: 'My Category',
description: 'My Description',
};
Way 4: Make the properties optional
方式 4:使属性可选
export interface Category {
name?: string;
description?: string;
}
const category: Category = {};
Way 5: Change your variable's type to use Partial<T>
方式 5:更改要使用的变量类型 Partial<T>
export interface Category {
name: string;
description: string;
}
const category: Partial<Category> = {};
回答by Vitor M. Barbosa
If you don't want to change your definition from interface
to class
, you could also do:
如果您不想将定义从 更改interface
为class
,您还可以执行以下操作:
let category = <Category>{ };
Otherwise, you could follow other answers and change your Category
to be a class.
否则,您可以按照其他答案并将您的更改Category
为一个班级。
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()
然后你尝试let x = {} as ITiered
,然后当你调用类似的东西时你会出错x.one.two.three()
回答by Serdar
In Typescript if you want to use Object Initializer you need to define all properties in the class.
在 Typescript 中,如果要使用 Object Initializer,则需要在类中定义所有属性。
let category: Category = {
name: '',
description: ''
};
With this way your model still can be remain as an interface.
通过这种方式,您的模型仍然可以保留为界面。
回答by Jake Holzinger
Your object literal must match the interface. Since your interface has two required properties (name
and description
) they must both be declared when the object is instantiated.
您的对象文字必须与接口匹配。由于您的接口有两个必需的属性(name
和description
),因此在实例化对象时必须同时声明它们。
const category: Category = {
name: 'foo',
description: 'bar'
};
If you cannot construct the entire object up front you can use the builtin Partial
type to build the object.
如果您不能预先构建整个对象,则可以使用内置Partial
类型来构建对象。
const builder: Partial<Category> = {};
builder.name = 'foo';
builder.description = 'bar';
const category: Category = builder as Category;
回答by nightingale2k1
interface Person{
id: number;
name: string;
}
let x: Person = {
id : 0,
name :"JOHN"
};
alert(x.name);
回答by user1983909
Like C# class:
像 C# 类:
export class Category {
category: number = null;
description: string = null;
name: string = null;
public constructor(init?: Partial<Category>) {
Object.assign(this, init);
}
}
Now when you create a new instance all field names are disponible and empty.
现在,当您创建新实例时,所有字段名称都是可处理的且为空的。
const instance_of_category: Category = new Category();
now you have emty class object with all fields defined like c#:
现在你有 emty 类对象,所有字段都像 c# 一样定义:
instance_of_category{
"category": null,
"description": null,
"name": null
}
回答by Subhashis Pal
If you already have a class and you want to create new instance and initialize properties at the same time you can try this
如果你已经有一个类并且你想同时创建新实例和初始化属性,你可以试试这个
return Object.assign(new Person(), {
name:"Your Name"
});