[英]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.