Figure out if object has a specific key

Figure out if object has a specific key

  
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?

here

Answer

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);
}
© 2024 Dagalaxy. All rights reserved.