5

So far I've tried:

function copyObject<K, V> (object: { [k: K]: V; }) {
    var objectCopy = {};

    for (var key in object)
    {
        if (object.hasOwnProperty(key))
        {
            objectCopy[key] = object[key];
        }
    }

    return objectCopy;
}

But this gives a compiler warning: "Index signature parameter type must be 'string' or 'number'".

Maybe it's possible to constrain the key type to number or string? Or just overload it with both types as keys?

0

2 Answers 2

8

You can simply do the following :

function copyObject<T> (object:T): T {
    var objectCopy = <T>{};

    for (var key in object)
    {
        if (object.hasOwnProperty(key))
        {
            objectCopy[key] = object[key];
        }
    }

    return objectCopy;
}

And usage:

// usage: 
var foo = {
    bar: 123
};

var baz = copyObject(foo);
baz.bar = 456;
Sign up to request clarification or add additional context in comments.

1 Comment

But that doesn't look like it restricts type T to be of type 'object' which means that you get no type errors even if you did, say: copyObject(5). The overload solution I added in my comment above, does give you a warning in that case so seems better.
1

Typescript doesn't have typeclasses and I'm not aware of any interface that only string and number types satisfy so overloading seems to be the only option:

export function copyObject<V> (object: { [s: string]: V; }) : { [s: string]: V; }
export function copyObject<V> (object: { [n: number]: V; }): { [n: number]: V; }
export function copyObject (object: {}): {}
export function copyObject (object: {}) {
    var objectCopy = <any>{};

    for (var key in object)
    {
        if (object.hasOwnProperty(key))
        {
            objectCopy[key] = (<any>object)[key];
        }
    }

    return objectCopy;
}

(The string and number overloads allow you to copy objects with homogeneous types)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.