[英]TypeScript initiate an empty interface object
Im building an app using angular 5 ( TS ), i got stuck trying to initiate an empty object of my interface.我正在使用 angular 5 ( TS ) 构建一个应用程序,我在尝试启动我的界面的空对象时被卡住了。
So the only acceptable solution i have seen is this one:所以我见过的唯一可以接受的解决方案是这个:
article: Article = {} as Article;
Although its seems legit it doesn't work;虽然它看起来是合法的,但它不起作用; trying to use article["something"] will fail because its just an empty object without any keys .尝试使用 article["something"] 会失败,因为它只是一个没有任何键的空对象。
The result im seeking looks something like this:我寻求的结果如下所示:
export interface Article {
slug: string;
title: string;
description: string;
body: string;
tagList: string[];
after init:初始化后:
article = { 'slug': '', 'title': '', 'description': '', body: '', tagList: '[]' }
An interface does not define an initial value for actual objects, but defines the requirements an object must meet for it to be an implementation of that interface.接口不定义实际对象的初始值,而是定义对象必须满足的要求才能成为该接口的实现。
You should create a factory of some kind that creates objects of type Article
, this could be as simple as this function:您应该创建一个某种类型的工厂来创建Article
类型的对象,这可以像这个函数一样简单:
const emptyArticle = (): Article => ({
slug: '',
title: '',
description: '',
body: '',
tagList: [],
});
You could additionally create a function that accepts an object that is a Partial<Article>
- as described here .您还可以创建一个接受Partial<Article>
对象的函数 - 如此处所述。 This enables you to pass a subset of initial values to the function.这使您能够将初始值的子集传递给函数。 This example uses emptyArticle
defined above:此示例使用emptyArticle
定义的emptyArticle
:
const createArticle = <T extends Partial<Article>>(initialValues: T): Article & T => {
return Object.assign(emptyArticle(), initialValues);
};
// Initialize a new article with a certain slug:
createArticle({ slug: 'my-awesome-article' });
Interfaces (and types in general) are just a compile time construct to help the compiler validate our code, as such the type assertion you use ( {} as Article
) will do nothing more than to tell the compiler that empty object literal has that shape.接口(和一般类型)只是一个编译时构造,用于帮助编译器验证我们的代码,因此您使用的类型断言( {} as Article
)只会告诉编译器空对象字面量具有该形状. If you want to have an 'empty' object for your interface, you will have to create it yourself:如果你想为你的界面创建一个“空”对象,你必须自己创建它:
interface Article {
slug: string;
title: string;
description: string;
body: string;
tagList: string[];
}
function emptyArticle(): Article {
return {
slug: '',
title: '',
description: '',
body: '',
tagList: []
}
}
The good news is that the compiler will warn you if you forget to add a default for any of the mandatory field.好消息是,如果您忘记为任何必填字段添加默认值,编译器会警告您。
Or if you want to make sure optional field are also specified you can create a mapped type that removes the optional from the fields.或者,如果您想确保还指定了可选字段,您可以创建一个映射类型,从字段中删除可选字段。
type Mandatory<T> = { [P in keyof T]-?: T[P] };
function emptyArticle(): Mandatory<Article> {
return {
....
}
}
Or more simply replace Interface
to Class
by setting default values like:或者更简单地通过设置默认值来替换Interface
到Class
:
export class Article {
slug: string = '';
title: string = '';
description: string = '';
body: string = '';
tagList: string[] = [];
}
When let article = new Article()
it will already have properties with default values当let article = new Article()
它已经具有具有默认值的属性
When you want to initialize an object without properties, then have to declare it that it is valid without properties.当你想初始化一个没有属性的对象时,那么必须声明它在没有属性的情况下是有效的。 Also the properties have to be optional:此外,属性必须是可选的:
export interface Article {
slug?: string;
title?: string;
description?: string;
body?: string;
tagList?: string[];
}
when not you have to initialize the object as you mentioned already如果不是,您必须按照您已经提到的方式初始化对象
article = { 'slug': '', 'title': '', 'description': '', body: '', tagList: '[]' }
Here is another way to initialize.这是另一种初始化方式。 Worked for me:为我工作:
const article: Article = ({} as any) as Article;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.