Reputation: 5825
const a = {
b: "hello",
c: "world",
}
function f(x: keyof typeof a | { x: string }) {
}
function g(x: string) {
if (a.hasOwnProperty(x)) {
return f(x);
} else {
return f({ x });
}
}
The g
function takes in a string x
. If x
is a key of a
("b"
or "c"
), then it should call the f
function with x
as the sole argument. If x
is NOT a key of a
, then the g
function has to call the f
function with an object which has the x
string inside it.
However, this code errors when calling the f(x)
function. It seems like TypeScript doesn't understand that after using hasOwnProperty
, the x
string is a keyof a
. Is there some way to make TypeScript understand this without resorting to type assertions?
Upvotes: 1
Views: 69
Reputation: 23692
I suggest with a type guard:
function isInA(x: string): x is keyof typeof a {
return a.hasOwnProperty(x);
}
if (isInA(x)) {
return f(x);
}
Upvotes: 4