Cine
Cine

Reputation: 4402

Typescript object conversion

How do I type a function, so that the input object is the same as the output object, but with different values?

//a has type { a: number;b: number }
let a = { 'a': 1, 'b': 1 };
interface IDictNumber {
   [key: string]: number;
}
interface IDictString {
   [key: string]: string;
}
function convert(f: IDictNumber) {
   return Object.keys(f)
      .reduce((p, v) => {
            p[v] = `${f[v]}`;
            return p;
         },
      {} as IDictString);
}
//b has type IDictString, but I wanted it to have { a: string;b: string }
let b= convert(a);

Upvotes: 0

Views: 158

Answers (2)

Cine
Cine

Reputation: 4402

This is now possible in TypeScript 2.1:

//a has type { a: number;b: number }
let a = { 'a': 1, 'b': 1 };
type Convert<T,K> = {
   [P in keyof T]: K;
};
function convertToString<T>(f: T) {
   let a  = <(keyof T)[]>Object.keys(f);
   return a.reduce((p, v) => {
            p[v] = `${f[v]}`;
            return p;
         },
      {} as Convert<T, string>);
}
let b = convertToString(a);

Upvotes: 2

Aleksey L.
Aleksey L.

Reputation: 37938

You could use generics for this:

let a = { 'a': 1, 'b': 1 };

interface A<T extends string|number> {
    [key: string]: T;
    a: T,
    b: T
}

function convert(f: A<number>) {
    return Object.keys(f)
        .reduce((p, v) => {
                p[v] = `${f[v]}`;
                return p;
            },
        {} as A<string>);
}

let b = convert(a);

Upvotes: 0

Related Questions