Reputation: 359
I want to use a variable as a type. For example, I declare a variable:
private readonly gridCol = 'grid-column';
private readonly sortCol = 'sort-column';
Now I can use the variable in functions instead of "hard coding" it:
return this.grid.querySelector(
`${this.gridCol}[data-role=selection]`
) as gridSelectionColumn<T> | undefined;
}
No problems. But I would like to use the variables I declared as the return type of below function, instead of hardcoding it, or use another variable with same name :
private getColumnTypeName(): 'sort-column' | 'grid-column' {
return this.sortable ? this.sortCol : this.gridCol;
}
Since this obviously does not work:
private getColumnTypeName(): this.sortCol | this.gridCol {
return this.sortable ? this.sortCol : this.gridCol;
}
Which will see the retun type as new declaration and return the following errors:
*
All declarations of 'sortCol' must have identical modifiers.ts(2687) Subsequent property declarations must have the same type. Property 'sortCol' must be of type '"sort-column"', but here has type 'any'.ts(2717)
Whats the best way to handle this kind of situation, syntax wise? The code is working as it is, but does not seem correct when I have to hardcode the return with the same valuable I have stored in a variable.
Upvotes: 1
Views: 839
Reputation: 282130
You can define string enums and use it like below
enum Direction {
SORT_COLUMNN = "sort-column",
GRID_COLUMNN = "grid-column",
}
private readonly gridCol = Direction.SORT_COLUMNN;
private readonly sortCol = Direction.GRID_COLUMN;
private getColumnTypeName(): Direction {
return this.sortable ? this.sortCol : this.gridCol;
}
or use an object with const assertion
const Direction = {
SORT_COLUMNN: "sort-column",
GRID_COLUMNN: "grid-column",
} as const;
private readonly gridCol = Direction.SORT_COLUMNN;
private readonly sortCol = Direction.GRID_COLUMN;
private getColumnTypeName(): typeof Direction[keyof typeof Direction]; {
return this.sortable ? this.sortCol : this.gridCol;
}
Upvotes: 2
Reputation: 85241
You can use the following syntax to look up the type on your class (you didn't give the class name, so i'm calling it "Example"):
class Example {
private readonly gridCol = 'grid-column';
private readonly sortCol = 'sort-column';
private getColumnTypeName(): Example["sortCol"] | Example["gridCol"] {
return this.sortable ? this.sortCol : this.gridCol;
}
}
If sortCol and gridCol were public, then it would also be possible to do this["sortCol"]
, but that doesn't work with private members
Upvotes: 1