如何在 TypeScript 或 Flow 中删除未定义的继承类型的联合类型细化
how to remove the union type refinement of of inherited type with undefined in TypeScript or Flow
我继承了一个类型,正在从库中导入,我想知道如何才能删除它对空值或未定义值的允许。
type Foo = {
baz: string
}
// Bar type is inherited and I would like to kill the union with undefined so I expect foo to never be falsey.
type Bar = {
foo?: Foo
}
const bar: Bar = {foo: {baz: 'baz'}};
// this destructuring issues an error because it allows for the possibility of it being undefined and undefined can't be destructured. And I can't conditionally exit since I'm using React hooks and I'd be violating the hooks should not be used conditionally rule
const {baz} = bar.foo;
内置的打字稿中有一个实用程序类型叫做Required,你可以像下面这样使用它
type Foo = {
baz: string
}
type Bar = {
foo?: Foo
}
type StrictBar = Required<Bar>
// type StrictBar = { foo: Foo } inferred
我继承了一个类型,正在从库中导入,我想知道如何才能删除它对空值或未定义值的允许。
type Foo = {
baz: string
}
// Bar type is inherited and I would like to kill the union with undefined so I expect foo to never be falsey.
type Bar = {
foo?: Foo
}
const bar: Bar = {foo: {baz: 'baz'}};
// this destructuring issues an error because it allows for the possibility of it being undefined and undefined can't be destructured. And I can't conditionally exit since I'm using React hooks and I'd be violating the hooks should not be used conditionally rule
const {baz} = bar.foo;
内置的打字稿中有一个实用程序类型叫做Required,你可以像下面这样使用它
type Foo = {
baz: string
}
type Bar = {
foo?: Foo
}
type StrictBar = Required<Bar>
// type StrictBar = { foo: Foo } inferred