我正在尝试如何输入一个对象,它的值依赖于键,这在下面的代码中有更好的解释。
我是这么试的:
// 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链接
1条答案
按热度按时间bn31dyow1#
使用mapped type
Playground