proutter类型中编码哪种类型的值。 例如,如果我有一个对象:
const inputObject: {
keyA: number;
keyB: boolean;
} = /* ... */;
我希望返回类型为:
{
keyA: "num";
keyB: "bool";
}
Record<"keyA" | "keyB", "num" | "bool">
SO,
transformObject
函数返回"num"
或
"bool"
作为给定对象中每个键的值。您可以如下实现:{ [Key in keyof Input]: TransformValue<Input[Key]> }
typecriptPlayground
type InputValue = number | boolean;
type TransformValue<IV extends InputValue> = IV extends number ? "num" : "bool";
const transformObject = <Input extends Record<string, InputValue>>(
input: Input
): { [Key in keyof Input]: TransformValue<Input[Key]> } => {
const result: any = {};
for (const key in input) {
result[key] = typeof input[key] === "number" ? "num" : "bool";
}
return result;
};
// Test case
const inputObject = {
keyA: 42,
keyB: true,
};
// { keyA: number; keyB: boolean; } --> { keyA: "num"; keyB: "bool"; }
const transformed = transformObject(inputObject);