我有一个这样的界面:
interface ISession {
emailAddress: string;
me: IUser | null;
groups: IGroup[] | null;
}
Run Code Online (Sandbox Code Playgroud)
我想用这个伪代码创建一个对象:
type SetAction = {
type: typeof SET,
key: K in keyof ISession,
value: V in valueof ISession
};
Run Code Online (Sandbox Code Playgroud)
该伪代码的问题是它不能确保值类型与 的值匹配ISession[k]。
这在TS中可能吗?
我遇到了类似的问题,这不是问题的一部分,而是为了帮助其他人思考,因为我觉得解决方案是相同的。我需要写一个函数function set(key, value)。其中key和value是适当的匹配对。
您可以创建这样的类型,但您想要做的是创建所有可能key/value组合的并集。所以我们要创建的类型是:
type SetAction =
{ type: typeof SET, key: 'emailAddress', value: string; } |
{ type: typeof SET, key: 'me', value: IUser | null; } |
{ type: typeof SET, key: 'groups', value: IGroup[] | null; }
Run Code Online (Sandbox Code Playgroud)
我们可以通过使用分布式条件类型来做到这一点
type SetAction = keyof ISession extends infer K ? // introduce type parameter
K extends keyof ISession ? // distribute over the type parameter
{ type: typeof SET, key: K, value: ISession[K]; } // The type that we construct for each K
: never: never
Run Code Online (Sandbox Code Playgroud)
或者使用映射类型的更容易理解的版本(结果是相同的):
type SetAction = {
[K in keyof ISession]-?: { type: typeof SET, key: K, value: ISession[K]; }
}[keyof ISession]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
825 次 |
| 最近记录: |