TypeScript initiate an empty interface object
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. 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:
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
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' });