简体   繁体   English

泛型:键入作为属性名称

[英]Generics: Type as property name

Is it possible with generics to pass an object for usage as not only the type, but as the key?泛型是否可以将对象不仅作为类型而且作为键传递使用?

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

When I do that, it says当我这样做时,它说

Property 'store' does not exist on type 'ajaxData' “ajaxData”类型上不存在属性“store”

Is there a way for me to access that property?有没有办法让我访问该属性? It works once compiled since all that is removed, but how can I get it working in the editor?自从所有内容都被删除后,它一旦编译就可以工作,但是我怎样才能让它在编辑器中工作?

Edit编辑

After thinking about it, I think I don't want the interface and the property to be the same.想了想,我想我不希望接口和属性是一样的。 I think I would want to use an interface with name x , so maybe something like this:我想我想使用名称为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

Yes if you have property name as explicit literal type, you can declare a type having property with that name by using mapped type syntax :是的,如果您将属性名称作为显式文字类型,则可以使用映射类型语法声明具有该名称的属性的类型

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

So the complete example should look like所以完整的例子应该看起来像

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