Search code examples
typescript

How to avoid getting a string as an index type


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)



Solution

  • Instead 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"

    working example

    Note however that LayerPropType is not of type string[] but rather string[] | undefined because the property CRS of WMSLayerProps is optional

    type of WMSLayerProps

    See working playground here