google / schema-dts

JSON-LD TypeScript types for Schema.org vocabulary
Apache License 2.0
860 stars 32 forks source link

Error TS4023 when importing types #168

Closed webdif closed 2 years ago

webdif commented 2 years ago

I have this piece of code:

import { SportsEvent, WithContext } from 'schema-dts';

const getStructuredData = (): WithContext<SportsEvent> => ({
  '@context': 'https://schema.org',
  '@type': 'SportsEvent',
  // ...
});

I have the error TS4023 on this:

Exported variable 'getStructuredData' has or is using name 'SportsEventLeaf' from external module 'myproject/node_modules/schema-dts/dist/schema' but cannot be named

How can I resolve this?

If I modify the schema.d.ts in my node_modules, and I export the SportsEventLeaf interface, it seems to solve this problem. But of course, it's not a real fix…

Eyas commented 2 years ago

Hmm, what TypeScript version are you using? 'Cannot be named' error were much more common in older versions of TS but I thought the checking here was relaxed.

webdif commented 2 years ago

I use TypeScript@3, do you think upgrading TypeScript does the trick?

Eyas commented 2 years ago

It's fixed starting TypeScript 3.9. You can upgrade to 3.9.7 or later.

BTW, if you don't want to upgrade, the fix is to give an explicit type to your function:

 import { SportsEvent, WithContext } from 'schema-dts';

-export const getStructuredData = (): WithContext<SportsEvent> => ({
+export const getStructuredData: ()=>WithContext<SportsEvent> = (): WithContext<SportsEvent> => ({
   '@context': 'https://schema.org',
   '@type': 'SportsEvent',
   // ...
 });
webdif commented 2 years ago

Thank you so much 🙂

chrisvltn commented 4 months ago

This started to happen again.

import {BreadcrumbList} from 'schema-dts';

const data: BreadcrumbList = {'@type': 'BreadcrumbList'};
export const exportedFunction = () => ({data});

Will show the error:

Exported variable 'exportedFunction' has or is using name 'BreadcrumbListLeaf' from external module "..." but cannot be named. ts(4023)

If the function isn't exported, the error seems to not appear, though.