2

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

2 Answers 2

1

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

2 Comments

The problem is that I need to pass it to an object property that is already defined as string and I would like to avoid creating const and then assigning { key: keyOfGame("id") }
@DanielStoyanoff your question was with variables and I answered it in that context. Unfortunately there is no other way to do it without an extra function if you are assigning to a field that is declared as type string
1

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.

3 Comments

Almost the same as creating a function, which I eventually did in a separate file -> keyOf<T>("prop")
But types don't pollute compiled code, if this was a concern for you. And as it was mentioned, it may be reasonable to move type checks to a place where constants are used. This isn't shown in the question.
Runtime type checking is not required. The ideas was to do it for compile time.

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.