0

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);

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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);

1 Comment

No that wont work, since i would call convert with { 'c':23, 'd': 45} and then not get the right type back

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.