![](/img/trans.png)
[英]Return type where one of the keys is computed from parameter in TypeScript 4.1
[英]Return type is object where key is computed from argument
下面我有一個函數getEntityPropId
,它返回一個對象有一個道具,像{ 'thingId': 1 }
串thing
被傳遞給函數。
我對如何讓函數返回類型包括鍵thingId
而不是僅包含任何字符串感到好奇,因為我正在傳遞知道返回值所需的所有信息。
但是我得到這個:
類型文字中的計算屬性名稱必須引用其類型為文字類型或``唯一符號''類型的表達式.ts(1170)
export const getEntityPropId = (value: any, entity: string): { [`${entity}Id`]: number } | null => {
const id = getEntityId(value, entity)
if (id !== null) return { [`${entity}Id`]: id }
return id
}
如果有必要,我可以設置一個enum
。
enum EntityPropIds {
thing = 'thingId',
}
export const getEntityPropId = (value: any, entity: EntityPropIds): { [EntityPropIds[entity]]: number } | null => {
const id = getEntityId(value, entity)
if (id !== null) return { [EntityPropIds[entity]]: id }
return id
}
這可能嗎?
TypeScript尚無法提供類型級別的動態屬性名稱(盡管在Github上的討論中存在一個未解決的問題 )
但是,正如您所建議的,如果您創建一個將實體映射到entityId的類型,則可能:
interface EntityIdMapping {
thing: 'thingId';
}
export const getEntityPropId = <T extends keyof EntityIdMapping>(value: any, entity: T): {[P in EntityIdMapping[T]]: number} | null => {
const id = getEntityId(value, entity)
if (id !== null) return { [`${entity}Id`]: id }
return id
}
我使用的是接口,而不是枚舉,因為它們更易於處理,並且不會引入任何運行時代碼。
接下來,我為entity
參數添加了通用類型,該類型必須是映射接口的鍵。
對於返回值,我們使用映射的類型,該類型在EntityIdMapping[T]
所有類型上循環。 在T = 'thing'
情況下,它只為接口中的match屬性返回一個條目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.