Home > Blockchain >  Keep object shape in functions with typescript
Keep object shape in functions with typescript

Time:03-22

function fn(obj: Record<string, any>) {
  return obj
}

const obj = { a: 1, b: 2, c: 3 }

// obj1's type: const obj1: Record<string, any>
const obj1 = fn(obj)

As you can see, I have a object with specific shape as argument for a function, and the function return a same shape object. What I want is get the return with most detailed shape(In my example is {a:number; b:number; c:number}) rather than a commonly used type.

CodePudding user response:

That's simple:

function fn<T>(obj: T) {
  return obj
}

const obj = { a: 1, b: 2, c: 3 }

// obj1's type: const obj1: {
//     a: number;
//     b: number;
//     c: number;
// }
const obj1 = fn(obj)

https://www.typescriptlang.org/play?ssl=9&ssc=18&pln=10&pc=18#code/GYVwdgxgLglg9mABMMAeAKgPgBRwEYBWAXIugJSIDeAUIogE4CmUI9S B1AvtdRAgGcoiDogC8VRAEMSARgA0iPCQBMiiCQDMiHtQD0ekYVkByAYigBPAA6MS-MEKMFZJGgbqeZiMCAC2eIz0ANz6hp5KJL4BQaEeERo -oEhYTp8gsIcsuLIYLiEZEA

  • Related