[Fixed] TypeScript initiate an empty interface object

Issue

Im building an app using angular 5 ( TS ),
i got stuck trying to initiate an empty object of my interface.

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 .

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: '[]' }

Solution

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:

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. This enables you to pass a subset of initial values to the function. This example uses emptyArticle defined above:

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' });

Leave a Reply

(*) Required, Your email will not be published