DEV Community

kay-adamof
kay-adamof

Posted on

How to provide detailed type information using "as" and "&"

Let's say you have created the following callback function:

const getMyPet = () =>
  document.documentElement.getAttribute('myPet')
// const getMyPet: () => string | null
Enter fullscreen mode Exit fullscreen mode

The return value of the function is string | null. However, since the argument is specified as myPet, there is a possibility that the returned value is a specific string.

Suppose you have created the following type in advance

type MyPet = 'tama' | 'pochi'
Enter fullscreen mode Exit fullscreen mode

Let's consider how to include the type MyPet in the return type of the getMyPet() function.

First, let's use the as keyword to specify the return type of the function:

const getMyPet = () =>
  document.documentElement.getAttribute('myPet') as MyPet
// const getMyPet: () => MyPet
Enter fullscreen mode Exit fullscreen mode

We have successfully specified the MyPet type. However, the null type is lost, so let's add it back:

const getMyPet = () =>
  document.documentElement.getAttribute('myPet') as MyPet | null
// const getMyPet: () => MyPet | null
Enter fullscreen mode Exit fullscreen mode

But with this, when we refer to the type information later, the specific contents of the MyPet type, i.e., 'tama' | 'pochi', will not be displayed. So let's use the intersection type: & to display the detailed information to TypeScript:

const getMyPet2 = () =>
  document.documentElement.getAttribute('myPet') as (MyPet & {}) | null
// const getMyPet2: () => "tama" | "pochi" | null
Enter fullscreen mode Exit fullscreen mode

The (MyPet & {}) part can also be written as (MyPet & string) to obtain the same type.

Please refer to the official documentation for more details on intersection types.

Although this may be sufficient, let's leave the possibility of receiving other strings besides 'tama' and 'pochi':

const getMyPet3 = () =>
  document.documentElement.getAttribute('myPet') as (MyPet & {}) | null | (string & {})
// const getMyPet3: () => "tama" | "pochi" | (string & {}) | null
Enter fullscreen mode Exit fullscreen mode

By adding (string & {}), we get a hint for creating a conditional statement in case a string other than "tama" or "pochi" is returned.

That's all.

You can check this example on the TS playground.

Top comments (0)