简体   繁体   English

Typescript:如何键入 object,其值取决于键

[英]Typescript: How to type an object whose values depend on the keys

I'm trying to How to type an object whose values depend on the keys.我正在尝试如何键入其值取决于键的 object。 This is better explained on the code below.这在下面的代码中有更好的解释。

This is what I tried:这是我试过的:

// Given this type
type Mapping = {
  "string": string;
  "number": number;
  "boolean": boolean;
};

// I want to create a type where the keys are the same as `Mapping`, but 
// the values are a function with the corresponding value of `Mapping` as
// the first argument.
type Property<K extends keyof Mapping> = Record<K, (value: Mapping[K]) => void>;

type Obj = Partial<Property<keyof Mapping>>;

const a: Obj = {
  // Right now, Typescript it says `value` is string | number | boolean.
  // I want Typescript to know that the type of `value` is boolean. 
  boolean: (value) => {
    console.log(value);
  }
}

Typescript Playground Link Typescript游乐场链接

Use a mapped type使用映射类型

type Mapping = {
    "string": string;
    "number": number;
    "boolean": boolean;
};

type Property<T extends Mapping> = {
    [K in keyof T]: (value: T[K]) => void
}

type Obj = Partial<Property<Mapping>>;

const a: Obj = {
    boolean: (value) => {
        console.log(value);
    }
}

Playground 操场

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

相关问题 在 TypeScript 中,如何获取值属于给定类型的 object 类型的键? - In TypeScript, how to get the keys of an object type whose values are of a given type? TypeScript 类型为 object 其值与其键匹配 - TypeScript type for object whose values match its keys 打字稿类型的对象,其键始终是具有一个通用参数的函数? - Typescript type of object whose keys are functions with one generic argument throughout? 如何基于 TypeScript 中的 const object 的键/值创建 object 类型? - How to create an object type based on keys/values of a const object in TypeScript? 如何键入 object,其键是另一种类型键的子集 - How to type an object whose keys are a subset of the keys of the another type 强制“keyof object”,排除值不是特定类型的键 - Enforce “keyof object”, excluding keys whose values are not a certain type Typescript:使用 object 值作为新类型的键 - Typescript: Use object values as keys for a new type Typescript:仅键入 object 个值,让 typescript 键入键 - Typescript: Only type object values and let typescript type the keys 如何从键中导出 Typescript 类型的值 - How to derive the values of a Typescript type from the keys 如何仅使用TypeScript声明属性为字符串类型的对象? - How to declare an object whose properties are of type string only using TypeScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM