最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

typescript - How to avoid getting a string as an index type - Stack Overflow

programmeradmin2浏览0评论

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
Add a comment  | 

2 Answers 2

Reset to default 1

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"

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>;
发布评论

评论列表(0)

  1. 暂无评论