1

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.

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Playground link

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.