Haocheng Haocheng - 5 months ago 23
Javascript Question

Extending Data Object in TypeScript

I'm trying to extending a data object in TypeScript, by adding some new fields. While I guess it's a quite common pattern in JavaScript, I can't make it be able to compile, without making

bar
as optional in the snippet as below.

I'm wondering is there any way to avoid making
bar
optional.
Any suggestion would be welcome, thank you.

interface BaseDataObject {
foo: string;
}

interface ExtendedDataObject extends BaseDataObject {
bar?: string;
}

function extendData(input : BaseDataObject) : ExtendedDataObject {
var output : ExtendedDataObject = input;
output.bar = input.foo + ' some suffix';
return output;
}

Answer

You can do this by compile-time casting input to ExtendedDataObject instead of just assigning it to output:

interface ExtendedDataObject extends BaseDataObject {
    bar: string;
}

function extendData(input : BaseDataObject) : ExtendedDataObject {
    var output = input as ExtendedDataObject;
    output.bar = input.foo + ' some suffix';
    return output;
}

This type of cast is officially called type assertion and it tells the compiler to trust you that the object can be treated as the type you indicate.

Comments