简体   繁体   English

如何告诉 Typescript 两个对象键必须相同?

[英]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 我希望foobar相同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:您可以创建给定泛型类型的所有可能的foobar组合的联合,如下所示:

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"

Playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何将 object 键的 map 值与 TypeScript 中的相同 object 相匹配? - How can I map values of object keys to the same object in TypeScript? 我如何告诉 TypeScript 两个变量具有相同的类型? - How do I tell TypeScript that two variables have the same type? 如何告诉 TypeScript 两个泛型类型相同? - How to tell TypeScript that two generic types are the same? 如何制作 typescript 类型,其中 object 中的所有键都具有相同的前缀? - How can I make a typescript type where all keys in object have same prefix? 如何告诉 Typescript 检查 object[key] 是否属于某种类型? - How can I tell Typescript to check that object[key] is of certain type? TypeScript:告诉对象它可以拥有哪些键和值 - TypeScript: Tell object which keys and values it can have 将对象属性约束为具有在 TypeScript 中的键必须相同的属性的对象 - Constrain objec properties to be object with properties whose keys must be the same in TypeScript 如何告诉 typescript 我正在使用特定枚举键的键传递 object? - How to tell typescript I'm passing object with a key of specific enum keys? 如何在 TypeScript 中使用可选键创建索引 object? - How can I create an indexed object with optional keys in TypeScript? 如何遍历打字稿中的两个对象键? - How to loop through two object keys in typescript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM