Issue
I have a const value:
const dataConst = 'constType'
And I want to enforce only this value in a certain interface, but this is not possible:
interface ExampleInterface {
data: dataConst
}
I tried this and it seems to work, but I don't know if it's the best practice:
interface ExmapleInterface {
data: typeof dataConst
}
I tried and succeeded, but I want to know if what I did is the best practice.
Solution
I believe there isn't a good or bad way of doing this. Your example is just one of the many ways of achieving what you want.
Perhaps an explanation of why your example works would be useful.
const dataConst = 'constType'
assigns an actual value to a dataConst
constant. You haven't specified the type explicitly for this const
so the type is inferred by the TypeScript compiler. It's smart so it will assign a "string literal" with a value "constType". In contrast, if you were to write something like: let dataConst = 'constType'
, the type of the dataConst
would be a simple string
because the compiler knows that the value can change in the future.
You can't use
interface ExampleInterface {
data: dataConst
}
because this is a type definition and only the "types" can go into it. In this case the dataConst
is the actual value.
In order to "retrieve" the type of the dataConst
constant we can use typeof
. Keep in mind this is a different operator from the Javascript one with the same name. It can only be used in the context of Typescript types.
interface ExampleInterface {
data: typeof dataConst
}
So now with that explanation out of the way is there any other way of doing it? Yes. For example:
declaring a type Value
based on value
type
const value = 'my-constant-value'
type Value = typeof value
interface Example {
prop: Value
}
or declaring Value
type with a string literal
type Value = 'my-constant-value'
const value: Value = 'my-constant-value'
interface Example {
prop: Value
}
or perhaps if you don't need an actual const value and just using the types is sufficient
type Value = 'my-constant-value'
interface Example {
prop: Value
}
or even
interface Example {
prop: 'my-constant-value'
}
Answered By - Aleksandr Šmailov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.