Home > Net >  Nullable type not being applied when exporting
Nullable type not being applied when exporting

Time:01-13

I have a hard time understanding why it wont apply my nullable type

Heres an example

interface Book {
  name: string;
  author: string;
  reference: string;
  category: string;
}

async function handleFetch<T>(endpoint: string, params: object): Promise<T | null> {
  const querystring = Object.entries(params)
    .map(([key, value]) => `${key}=${value}`)
    .join('&');

  try {
    const response = await fetch(`/api/${endpoint}?${querystring}`);
    const data = await response.json();

    if (response.ok) {
      return data[0] || null;
    }

    return null;
  } catch {
    throw new Error('Internal error');
  }
}

export default {
  getBook: (reference: string) => {
    return handleFetch<Book>('books', { reference });
  },
};

I can see that the method returns a nullable type enter image description here

but when exporing it isn't nullable anymore enter image description here

I feel like I am missing something but have never encountered that before

thank you

CodePudding user response:

The only cause of this I can think of would be that the strictNullChecks compiler option is off. This is also included by the "strict" compiler option

Try adding:

"strict": true,

Or:

"strictNullChecks": true,

to your tsconfig.json file under the "compilerOptions" section.

In strict mode, your code seems to work fine. See this sandbox.

  •  Tags:  
  • Related