为什么只读对象需要对象中的可选属性?

问题描述 投票:0回答:1

这是我的示例代码:

/* @flow */

type A = {
    var1 : number,
}

type B = $ReadOnly<{
    var1 : number,
    var2? : string,
}>

let v : A = { var1: 1 };
let w : B =  v;

和流错误:

    13: let w : B =  v;
                     ^ Cannot assign `v` to `w` because property `var2` is missing in `A` [1] but exists in object type [2].
        References:
        12: let v : A = { var1: 1 };
                    ^ [1]
        13: let w : B =  v;
                    ^ [2]

我知道通常不能将A强制转换为B,因为这将允许分配v.var2。我认为将B设置为ReadOnly可以避免这种情况。因此,我不了解这种强制转换会成为问题的情况。

flowtype
1个回答
0
投票

这里的问题是

type A = {
    var1: number,
};

方法将A定义为对象,其属性var1number,所有其他属性为unknown

例如:

type A = {
    var1: number,
};
type C = {
    var1: number,
    var2: boolean,
};

let c: C = { var1: 1, var2: true };
let a: A = c;

有效,因为A类型与C兼容。

但是,如果我们随后在类似于您的代码的代码段中添加:

type B = {
    var1: number,
    var2?: string,
};
let b: B = a;

事实上,由于b.var2,因此将string|void视为boolean

© www.soinside.com 2019 - 2024. All rights reserved.