联合类型中的Typescript null无效



interface Address {
a: string
}
interface End {
state: {
addrList: null | (Address[]);
};
}
class End {
state = {
addrList: [{
a: '1'
}],
};
}

Error: Subsequent property declarations must have the same type. 
Property 'state' must be of type '{ addrList: Address[] | null; }', but here has type '{ addrList: { a: string; }[]; }'.

然后我得到了这个。

那么,我是不是错过了什么?

https://www.typescriptlang.org/play?ts=4.0.2#code/JYOwLgpgTgZghgYwgAgIIBN1QgZx8gbwChlk4AuZHMKUAcyIF8ijRJZEUBREdQkqmDiRKxUqTiYoAGWDVKIAK4AbZcgA+yABQYsuHAG0AugEoA3AMYXmRBmr5kPPmHCUAXn7iyU2fOQDVx8KZAByAEYwgVJGIwAaS2sgA

在线演示

您忘记实现接口,这就是为什么End类不知道应该向addrList分配什么。此外,接口的名称之前应该有I(这只是模式(,这样可以避免名称冲突。

看看这个

interface IAddress {
a: string
}
interface IEnd {
state: {
addrList: (IAddress[] | null);
};
}
class End implements IEnd {
state = {
addrList: [{
a: '1'
}],
};
}

最新更新