admin管理员组文章数量:1391981
Given
type Maybe<T> = T | undefined;
class Obj {
jbo: Maybe<Jbo>;
}
, is it possible to define a function that given a o: Maybe<Obj>
asserts the types of both o
and o.jbo
?
I'm thinking of something like:
function everythingIsDefined(o: Maybe<Obj>):o is Obj && o.jbo is Jbo {
// checks in here
}
Given
type Maybe<T> = T | undefined;
class Obj {
jbo: Maybe<Jbo>;
}
, is it possible to define a function that given a o: Maybe<Obj>
asserts the types of both o
and o.jbo
?
I'm thinking of something like:
function everythingIsDefined(o: Maybe<Obj>):o is Obj && o.jbo is Jbo {
// checks in here
}
Share
Improve this question
edited Jul 27, 2017 at 17:05
gen
asked Jul 27, 2017 at 16:50
gengen
10k14 gold badges37 silver badges66 bronze badges
2 Answers
Reset to default 8A user-defined typeguard can only return one x is T
. Luckily, you can use unions and intersections in your choice of T
. So, for example:
function everythingIsDefined(o: Maybe<Obj>): o is Obj & {jbo: Jbo} {
return typeof o !== 'undefined' && typeof o.jbo !== 'undefined';
}
The everythingIsDefined
function asserts that the input is both an Obj
(as opposed to undefined), and an object whose jbo
property is a Jbo
(as opposed to undefined). So you can use it like this:
if (everythingIsDefined(obj)) {
console.log(obj.jbo.toString()) // no error
}
Yeah, you can pull that off:
type Maybe<T> = T | undefined;
type DeepMaybe<T> = { [K in keyof T]: Maybe<T[K]> };
class Obj {
jbo: Jbo;
}
function everythingIsDefined<T>(o: DeepMaybe<T>): o is T {
return false;
}
And then:
let obj: DeepMaybe<Obj> = {} as Obj;
if (everythingIsDefined(obj)) {
// type of obj.jbo is Jbo
} else {
// type of obj.jbo is Maybe<Jbo>
}
(code in playground)
Explanation:
There's probably no way to aplish that with the types you provided (that is Obj.jbo: Maybe<Jbo>
).
Instead, the class Obj
needs to define its properties as the actual type, but if you type your variable as DeepMaybe<Obj>
(or anything else instead of Obj
) then you get the same thing.
The difference is now, because DeepMaybe
is a mapped type you have better control on how to create the type guard.
本文标签: javascriptIs it possible to combine user defined type guards in TypeScriptStack Overflow
版权声明:本文标题:javascript - Is it possible to combine user defined type guards in TypeScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744687910a2619816.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论