1
votes

What is causing this code to fail?

interface ISomeData {
    name: string;
}

class SomeData implements ISomeData {
    name: string = "adam";
}

class SomeClass<T extends ISomeData> {
    constructor(dataTemplate?: T) {
        this.dataTemplateInternal = dataTemplate;
    }

    private dataTemplateInternal: T;

    public initSomeData() : T {
        let data: T = new SomeData();
        if (this.dataTemplateInternal) {
            return this.dataTemplateInternal;
        }
        return data;
    }
}

The first line of "initSomeData" has an error saying

Type 'SomeData' is not assignable to type 'T'

But since my generic constraint is based on an interface, which SomeData implements, shouldn't that be sufficient?

Ridiculously long link to this code in the TypeScript Playground

1

1 Answers

2
votes

If you'd do:

let data: ISomeData = new SomeData();

You wouldn't get this error, but T is not ISomeData, it is something "more" than ISomeData, for example it can be:

interface IMoreData extends ISomeData {
    username: string;
}

And then you say that:

let data: IMoreData = new SomeData();

Which isn't right as it's missing the username property.
You can solve this by telling the compiler that you know what you're doing (AKA casting):

let data: T = new SomeData() as T;

Or just:

let data = new SomeData() as T;