是否可以使用泛型将对象不仅作为类型,而且作为键来传递?
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
当我这样做时,它说
Property 'store' does not exist on type 'ajaxData'
我有办法访问该属性吗?它一旦编译就可以工作,因为所有的东西都被删除了,但是我怎样才能让它在编辑器中工作?
编辑
想了想,我觉得不希望接口(interface)和属性是一样的。我想我想使用名称为 x
的 interface
,所以可能是这样的:
let res1 = await get<storeA, 'category'>('/my/url1')
let res2 = await get<storeB, 'catList'>('/my/url2')
res1.data.category.category
res2.data.catList.categories
最佳答案
是的,如果您将属性名称作为显式文字类型,您可以使用 mapped type syntax 声明具有该名称属性的类型:
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
}
关于javascript - 泛型 : Type as property name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47044401/