Extending a data object in TypeScript

I am trying to extend a data object in TypeScript by adding a few new fields. Although I assume this is a fairly common JavaScript pattern, I cannot compile it without making barit optional in a snippet, as shown below.

I am wondering if there is a way to avoid being baroptional. Any suggestion would be welcome, thanks.

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;
}
+4
source share
1 answer

You can do this by casting inputto ExtendedDataObject, instead of just assigning it 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;
}

type assertion, , , , .

+4

All Articles