typescript - Type guards to convert interface X into Required?
问题描述
I have an interface Foo
with an optional field and want to call a function that takes Required<Foo>
. Is there a type-safe way of calling this function? For example
interface FooBar {foo:string, bar?: string}
const myFooBar:FooBar = {foo:'foo'}
if (myFooBar.bar !== undefined) {
test(myFooBar)
}
function test(fooBar: Required<FooBar>) {
console.log(fooBar.bar)
}
but the compiler reports
Argument of type 'FooBar' is not assignable to parameter of type 'Required<FooBar>'.
Types of property 'bar' are incompatible.
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.(2345)
I could just myFooBar explicitly but does anyone know of a type-safe of doing this that doesn't involve casting.
解决方案
You can use a type guard function for that:
function hasBar(fooBar: FooBar): fooBar is Required<FooBar> {
return typeof myFooBar.bar !== "undefined";
}
Then
if (hasBar(myFooBar)) {
test(myFooBar)
}
It doesn't have to be so specific to the FooBar
type if you don't want it to be. It could be specific to the fact that bar
is type string
:
function hasBarString<T>(fooBar: T): fooBar is T & {bar: string} {
return typeof myFooBar.bar === "string";
}
const myFooBar:FooBar = {foo:'foo'}
if (hasBarString(myFooBar)) {
test(myFooBar)
}
推荐阅读
- ios - 如何将一系列拖动点与一系列 CGPoint 路径匹配?
- python - Fillna 通过使用创建的函数关联多个列
- python - 我想更改列表,使其连续两次具有相同的值
- reactjs - 如何用玩笑测试 Next.js 的 getServerSideProps
- javascript - 如何在可见时播放 html 视频
- node.js - 当依赖包的所有者从 github 中删除存储库时,Golang 项目会发生什么?
- c - 如何测量libuv中的延迟?
- node.js - react native 中的密码重置不起作用
- r - 如何在 R 中碱基对图的空白空间中添加图例?
- visual-studio-2019 - Visual Studio 2019 调试观察窗口