如何定义记录的返回类型,并返回具有相同属性的记录,但具有转换的值类型

问题描述 投票:0回答:1
我希望能够在类型

proutter类型中编码哪种类型的值。 例如,如果我有一个对象:

const inputObject: {
  keyA: number;
  keyB: boolean;
} = /* ... */;
我希望返回类型为:

{ keyA: "num"; keyB: "bool"; }

当前

Record<"keyA" | "keyB", "num" | "bool">

的标准。这可能吗?
    

SO,
transformObject
函数返回

"num"

"bool"

作为给定对象中每个键的值。您可以如下实现:
typescript
1个回答
0
投票
{ [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);
    
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.