[英]How can I tell Typescript that two object keys must be the same?
I want to define a type over a JS/TS record (ie, something with keys and values):我想在 JS/TS 记录上定义一个类型(即带有键和值的东西):
type Args<R extends object> = {
foo: keyof R
bar: keyof R
}
How can I tell Typescript that I want foo
and bar
to be the same keyof R
?如何告诉 Typescript 我希望foo
和bar
是相同的keyof R
?
I can do this:我可以做这个:
type Args<R extends object, K extends keyof R> = {
foo: K
bar: K
}
But then all clients of the Args
type to have to manually specify type K
:但是所有Args
类型的客户端都必须手动指定类型K
:
type Pizza = {
name: string
radius: int
}
const myArgs: Args<Pizza, 'name'> = { foo: 'name', bar: 'name' }
Typescript should be able to infer this, I would think.我认为打字稿应该能够推断出这一点。 But how do I write the type?但是我该如何写类型呢?
This is possible.这个有可能。 You can create a union of all possible foo
and bar
combinations of a given generic type like this:您可以创建给定泛型类型的所有可能的foo
和bar
组合的联合,如下所示:
type Args<R extends object> = {
[K in keyof R]: {
foo: K,
bar: K
}
}[keyof R]
This will lead to the desired behaviour:这将导致所需的行为:
type Pizza = {
name: string
radius: number
}
const myArgs1: Args<Pizza> = {
foo: 'name',
bar: 'name'
}
const myArgs2: Args<Pizza> = {
foo: 'name',
bar: 'radius'
} // Error: "name"' is not assignable to type '"radius"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.