Daniel Stoyanoff
Daniel Stoyanoff

Reputation: 1564

Typescript - keyof without a function

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?

enter image description here

Upvotes: 2

Views: 777

Answers (2)

Estus Flask
Estus Flask

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

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

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

Related Questions