繁体   English   中英

泛型:键入作为属性名称

[英]Generics: Type as property name

泛型是否可以将对象不仅作为类型而且作为键传递使用?

interface store {
  category: string
}

interface ajaxResponse<T> {
  data: ajaxData<T>
  errors: string[]
  success: boolean
}

interface ajaxData<T> {
  rewards: {
    amount: number
    error: string
  }
  T: T
}

function get<T>(url): Promise<ajaxResponse<T>> {
    // make ajax GET request
    // return json object
}

let res = await get<store>('/my/url')

res.data.store.category

当我这样做时,它说

“ajaxData”类型上不存在属性“store”

有没有办法让我访问该属性? 自从所有内容都被删除后,它一旦编译就可以工作,但是我怎样才能让它在编辑器中工作?

编辑

想了想,我想我不希望接口和属性是一样的。 我想我想使用名称为xinterface ,所以可能是这样的:

let res1 = await get<storeA, 'category'>('/my/url1')
let res2 = await get<storeB, 'catList'>('/my/url2')

res1.data.category.category
res2.data.catList.categories

是的,如果您将属性名称作为显式文字类型,则可以使用映射类型语法声明具有该名称的属性的类型

type A<T, PropertyName extends string> = {[P in PropertyName]: T}

所以完整的例子应该看起来像

interface store {
  category: string
}

interface ajaxResponse<T, PropertyName extends string> {
  data: ajaxData<T, PropertyName>
  errors: string[]
  success: boolean
}

type ajaxData<T, PropertyName extends string> = {
  rewards: {
    amount: number
    error: string
  }
} & {[P in PropertyName]: T}




function get<T, PropertyName extends string>(url): Promise<ajaxResponse<T, PropertyName>> {
    // make ajax GET request
    // return json object
  return null;
}

async function test() {
  let res = await get<store, 'store'>('/my/url')

  res.data.store.category
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM