Typescript允许类属性具有多种类型

时间:2018-11-09 14:07:11

标签: typescript

在Typescript中,我有两个类,Foo和Bar

export class Foo{
  data: Bar<Types>
}

export class Bar<T>{
  attributes: T
}

此外,我还有一个类型

export type Types = Circle | Square

接下来我声明我的变量

x: Bar<Circle>

但是当我想通过这样做为这个变量赋值时

x = someRandonJsonData

我收到以下类型错误:

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

我想知道我的错误在哪里?

1 个答案:

答案 0 :(得分:2)

简短版本:

create table rolemaster(roleno int(2) not null,
                        primary key(roleno),
                        rolename varchar(20));

create table roombed(roomnumber varchar(10),
                     bednumber varchar(10) not null primary key,
                     username varchar,
                     foreign key(username) references roleusers(username));

问题在于let x: Bar<Circle>; let z: Bar<Types>; x = z; 是一个更广泛的类型,因为它可能与zBar<Circle>等效-后者不兼容;因此您需要使用类型防护来缩小它的大小:

Bar<Square>

这是一个完整的例子:

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

if (isCircle(z)) {
    x = z;
}
相关问题