[英]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);
}
}
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.