I'm building an app using React Native with TypeScript. I'm writing my own custom wrapper around a function of the React Native Keychain package.
export const getToken = () => getGenericPassword().then(creds => creds.password);
The problem is that the type of getGenericPassword() is:
function getGenericPassword(
options?: Options
): Promise<boolean | {service: string, username: string, password: string}>;
And my linter complains that the key password does not exist if creds is of type boolean.
Property 'password' does not exist on type 'boolean | { service: string; username: string; password: string; }'.
Property 'password' does not exist on type 'false'.
How can I pick one of these values?
If the value is a Boolean, it doesn't have those properties. You have to first handle the case that the result is a Boolean:
TypeScript understands that inside the
ifbranch the result is a boolean and inside theelsebranch it's not, so it must be your dictionary type.If Typescript didn't work like this, you could write code that ignores the case that the promise returns a Boolean, and you'd cause a runtime problem later when you try to read
.passwordfrom afalse