0

In Typescript I have two classes, Foo and Bar

export class Foo{
  data: Bar<Types>
}

export class Bar<T>{
  attributes: T
}

Next to that I also have a type

export type Types = Circle | Square

Next up I declare my variable

x: Bar<Circle>

But when I want to assign a value to this variable by doing

x = someRandonJsonData

I get the following type error:

Type 'Bar<Types>' is not assignable to type 'Bar<Circle>'.

I'm wondering where my mistake is in all of this ?

2
  • What is the type of someRandonJsonData. If it is Bar<Types> this error is expected.. and it's there for the same reason you can't assign a value of type Types to a variable of type Circle Commented Nov 9, 2018 at 14:11
  • It is indeed Bar<Types>. So how would I be able to make my Bar property attributes to either be Circle or Square ? Commented Nov 9, 2018 at 14:19

1 Answer 1

2

Short version:

let x: Bar<Circle>;

let z: Bar<Types>;

x = z;

The problem is that z is a wider type, because it could be the equivalent of Bar<Circle> or Bar<Square> - and the latter is not compatible; so you need to narrow it with a type guard:

function isCircle(item: Bar<Types>): item is Bar<Circle> {
    return (item.attributes.hasOwnProperty('radius'));
}

if (isCircle(z)) {
    x = z;
}

Here's a full example:

interface Circle {
    radius: number;
}

interface Square {
    width: number;
}

type Types = Circle | Square

class Foo{
  data: Bar<Types>
}

class Bar<T>{
  attributes: T
}

let x: Bar<Circle> = {
    attributes: {
        radius: 4
    }
};

let y: Bar<Square> = {
    attributes: {
        width: 4
    }
};

let z: Bar<Types> = {
    attributes: {
        radius: 4
    }
};

// Error, as it may not be compatible
x = z;

function isCircle(item: Bar<Types>): item is Bar<Circle> {
    return (item.attributes.hasOwnProperty('radius'));
}

if (isCircle(z)) {
    // Works
    x = z;
}
Sign up to request clarification or add additional context in comments.

Comments

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.