N
N
Nikita Sokolov2021-08-04 09:17:17
typescript
Nikita Sokolov, 2021-08-04 09:17:17

How to do proper type checking?

There is such a code

const installed = window.getOfflineSigner && window.keplr 

const enable = () => {
  if (installed) return window.keplr.enable(chainId)
}


Keplr is a browser extension so I need to check if it is installed. Since Installed is just bool ts, it doesn't understand that window has keplr. If you pass the full condition, then everything works as it should. But I would like not to write it everywhere. How to make such code work? Naturally without an operator! after keplr.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Belyaev, 2021-08-05
@wb_by

https://www.typescriptlang.org/docs/handbook/2/nar...

type Keplr = {
  enable(chainId: ChainId): Enable;
};
const isInstalled = (v: unknown): v is Keplr => !!(window.getOfflineSigner && v) 

const enable = () => {
  if (isInstalled(window.keplr)) return window.keplr.enable(chainId)
}

Well, either wait for the release of 4.4 or switch to beta:
https://devblogs.microsoft.com/typescript/announci...

W
WbICHA, 2021-08-04
@WblCHA

https://www.typescriptlang.org/docs/handbook/relea...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question