Typescript:如何键入值依赖于键的对象

xvw2m8pv  于 2023-01-27  发布在  TypeScript
关注(0)|答案(1)|浏览(92)

我正在尝试如何输入一个对象,它的值依赖于键,这在下面的代码中有更好的解释。
我是这么试的:

// 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链接

bn31dyow

bn31dyow1#

使用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

相关问题