I am working through an example in an ASP.Net Core 6 and Angular 13 book on Material Tables, paging, sorting and filtering.
The material table in my angular component html looks like this:
<table mat-table [dataSource]="cities"
[hidden]="!cities"
matSort (matSortChange)="loadData()"
[matSortActive]="defaultSortColumn"
[matSortDirection]="defaultSortOrder">
And in the component ts file or the controller, it has defaultSortOrder initialized like this:
public defaultSortOrder: "asc" | "desc" = "asc";
I don't understand this syntax. I read it as: "asc" OR "desc" is assigned "asc".
It seems to work but I don't understand what is going on here. If I try to initialize it to just "asc",
public defaultSortOrder = "asc";
it says: "Type 'string' is not assignable to type 'SortDirection'."
I tried to read the documentation but I still don't get it.
What does this syntax mean?
public defaultSortOrder: "asc" | "desc" = "asc";
CodePudding user response:
The code "asc" | "desc"
is simply declaring the type for defaultSortOrder
. It is specifying a union of string literal types, which just means the type is a string of either 'asc'
or 'desc'
.
The code = "asc";
is simply assigning the initial value to defaultSortOrder
.
The reason you receive an error when you omit the type is because Typescript infers the type from the assigned value as any string
but the component requires a narrower type of a string with values'asc' | 'desc'
.
So instead of reading as
"asc" OR "desc" is assigned "asc".
Read as:
A variable allowed to have the values "asc" or "desc" is assigned "asc"
CodePudding user response:
The type can be either of the two values. If you set the value as 'test'
you will get a type error.
this.defaultSortOrder = "test"; // <- type error!
So we can use this method of defining, when you want the property to have only certain values, in this case asc
or desc
!