I recently updated to TypeScript version ~3.1.6 and defined an interface called Shop as follows:
export interface Shop {
readonly displayName: string;
name: string;
city: string;
}
In this interface, the property displayName
is set by the backend and cannot be altered by the user interface.
To create a new Shop instance, I implemented a Service that makes a REST call with properties city
and name
:
createShop = (shop: Partial<Shop>) =>
this._http.post(`/shop/new`, shop, this._options)
.pipe(
catchError(this.handleError)
);
When passing data from an Angular 7 reactive form, it looks like this:
createShop = () =>
this._shopService.createShop({
name: this.form.get('name').value,
city: this.form.get('city').value
}).subscribe(/* handlers */);
I used the type Partial<Shop>
for the create method's shop parameter to avoid creating a separate <CreateShop>
interface, assuming that was the purpose of Partial<T>
.
However, during compilation, I encountered this error:
src/app/addShop.component.ts(39,40): error TS2345: Argument of type '{ name: string; city: string; }' is not assignable to parameter of type 'Shop'.
Property 'displayName' is missing in type '{ name: string; city: string; }'.
By defining a new interface CreateShop
which extends Partial<Shop>
, I was able to resolve this compilation issue.
Why am I unable to use inline declaration for Partial
?
Especially when it goes against what is suggested in Partial<T> only works with inline values