Reputation: 1564
I am facing the following issue and I am not sure how to approach it. I want to assign a name of property to a string property of another object. Not sure however how to use key of in this case.
I managed to do it using "validation" function, just to have compile errors, but I would like to skip declaring a function that does nothing. Any ideas?
Upvotes: 2
Views: 777
Reputation: 222503
It's possible to use same approach as in this answer in order to segregate type checking from JS output:
type CheckGameProp<T extends keyof IGame> = T;
const invalidColumn = "invalidColumn";
{ type _checkGameProp = CheckGameProp<typeof invalidColumn>; }
const validColumn = "id";
{ type _checkGameIdProp = CheckGameProp<typeof validColumn>; }
_checkGameIdProp
dummy type can be scoped to avoid problems with type name choice.
Depending on how invalidColumn
and validColumn
are used, it may be better to check them where they are used instead.
Upvotes: 1
Reputation: 249666
Type assertions are there to let you do things the compiler thinks are invalid. Just declare the type of const
explicitly, :
interface IGame { id: number}
const incalidColumn: keyof IGame = 'invalild' // error
const validColumn: keyof IGame = 'id'
Upvotes: 1