[英]Typescript - Get property of name with string, as generic type
我扼殺了標題,不確定我想做的事情的技術術語。 當我同時在 F# 和 Typescript 中學習它們時,類型約束對我來說有點令人難以置信。
我有一個接口狀態變量,它包含頁面上所需的每種類型數據的列表
interface state{
clients: clients[]
appointments: appointments[]
...
}
const ApplicationState : state = {...}
我想要一個通用函數,可用於通過 id 獲取特定客戶、約會。
所以看起來像
getData('clients', 2)
我首先定義了一種允許的屬性(如果有更好的方法讓我知道)。
type entity = "clients" | "appointments"
但是我能得到ApplicationState
的屬性嗎?
那么getData
函數可能看起來像這樣嗎?
const getData = (foo: entity, id: number) => {
ApplicationState.magicallyGetPropertyByName.filter(entity => entity.id = foo.id)
}
在保持類型推斷的同時這可能嗎?
謝謝
這里的主要問題是你不能像這樣在聯合上調filter
:
type Clients = {
tag: 'Clients'
id: number
}
type Appointments = {
tag: 'Appointments'
id: number
}
declare const test: Clients[] | Appointments[]
test.filter(elem => elem)
但是,有一個解決方法:
type Clients = {
tag: 'Clients'
id: number
}
type Appointments = {
tag: 'Appointments'
id: number
}
type State = {
clients: Clients[]
appointments: Appointments[]
}
type Entity = keyof State;
declare const ApplicationState: State
const withState = <
S extends Record<string, { id: number }[]>
>(state: S) =>
<E extends keyof S>(prop: E, id: number) =>
state[prop].filter(entity => entity.id === id)
const getData = withState(ApplicationState);
getData('clients', 2)
Playground您可能已經注意到,我已經將State
聲明為一種type
而不是interface
。 這是因為默認情況下interfaces
未編入索引。 如果將其改回interface
, withState
將導致錯誤。
事實上,您不需要知道clients
和appointments
確切類型,您只需要確保所有這些類型都具有公共屬性id
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.