我正在寻找一种方法来正确地对这种情况进行类型化,在这种情况下,var可以是定义的,也可以是空的。
我目前的做法是通过Partial,但结果并不准确。
更大的上下文是mobx observates,开始是空的,但稍后通过网络填充。所以它们的初始状态是空的,但是一旦定义,它就被定义了。
你可以在this playground玩它。

// Definition
interface Foo {
  a: string;
  b: number;
}

// Bar could be an empty object.
type Bar = Foo | {};

let bar: Bar = {};

// Fails for obvious reasons -
bar.a = '10'

// Making it Parial fixes the issues, but lies about the structure.
// Instead of it being either all required or empty, it's becomes optional which is a falsey state.a
type Baz = Foo | Partial<Foo>;

let baz: Baz = {};
baz.a = '123';

最佳答案

我通常在这样的场景中进行空对象分配,这样,在网络请求填满一个属性之前,我会得到一个更好的类型,使用该属性的风险很小。
所以我会将类型作为一个完整的类型,并对空对象的赋值进行强制转换。

interface Foo {
  a: string;
  b: number;
}

let foo: Foo = {} as Foo;

foo.a = '10' // will work

关于reactjs - 如何键入可选的空对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57865326/

10-12 05:04