Issue
Let's say, I have an interface like this:
interface field {
code: string
name: string
// ...
}
Then I want to create a variable with a value that only accepts members from that interface:
let key: "code" | "name" // ...
It will be a very wide line of code if there are many interface members, is there a solution for this?
Is there a quick solution to validate a variable based on the members of the interface using TypeScript as above?
Solution
That is the use case for the keyof
type operator:
The
keyof
operator takes an object type and produces a string or numeric literal union of its keys.
interface field {
code: string
name: string
// ...
}
let key: keyof field;
key = "code"; // Okay
key = "other"; // Type '"other"' is not assignable to type 'keyof field'.
Answered By - ghybs
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.