i am trying to find a type from a type using a string as an index type (which does not work). how do i solve that mystery, that LayerPropType will be of type string[] in this example?
is there any way?
type WMSLayerProps = {
Name?: string
CRS?: string[]
}
type WMSStyleProps = {
Name?: string
Title?: string
}
const OGCWMSLayerProps: (keyof WMSLayerProps)[] = [
'Name',
'CRS',
]
const OGCWMSStyleProps: (keyof WMSStyleProps)[] = ['Name', 'Title']
const tagName = "CRS"
// LayerPropType should be of type string[]. but instead i cannot use tagName
// as an indexType
type LayerPropType = WMSLayerProps[tagName]
// this is the error message:
// Type 'tagName' cannot be used as an index type.ts(2538)
// 'tagName' refers to a value, but is being used as a type here. Did you mean 'typeof
// tagName'?ts(2749)
i am trying to find a type from a type using a string as an index type (which does not work). how do i solve that mystery, that LayerPropType will be of type string[] in this example?
is there any way?
type WMSLayerProps = {
Name?: string
CRS?: string[]
}
type WMSStyleProps = {
Name?: string
Title?: string
}
const OGCWMSLayerProps: (keyof WMSLayerProps)[] = [
'Name',
'CRS',
]
const OGCWMSStyleProps: (keyof WMSStyleProps)[] = ['Name', 'Title']
const tagName = "CRS"
// LayerPropType should be of type string[]. but instead i cannot use tagName
// as an indexType
type LayerPropType = WMSLayerProps[tagName]
// this is the error message:
// Type 'tagName' cannot be used as an index type.ts(2538)
// 'tagName' refers to a value, but is being used as a type here. Did you mean 'typeof
// tagName'?ts(2749)
Share
Improve this question
edited Feb 6 at 8:19
jonrsharpe
122k30 gold badges266 silver badges473 bronze badges
asked Feb 6 at 8:18
pcacepcace
6627 silver badges21 bronze badges
2 Answers
Reset to default 1Instead of type LayerPropType = WMSLayerProps[tagName]
you should use type LayerPropType = WMSLayerProps[typeof tagName]
(note the typeof on the index)
This is because you're declaring a type, so you must use the type to access the property, not its value. In this case both are "the same" because tagName is a constant, so its type is not string but rather "CRS"
Note however that LayerPropType
is not of type string[]
but rather string[] | undefined
because the property CRS
of WMSLayerProps
is optional
See working playground here
You can't directly access dynamic properties in TypeScript types. You need to use generics to achieve this.
type GetPropertyType<T, K extends keyof T> = T[K];
type LayerPropType = GetPropertyType<WMSLayerProps, typeof tagName>;