Import and export TS types and interfaces in Next.js app don't needed anymore? #50684
-
SummaryHello! If I have this code in types.ts file:
and this code in my page.tsx file:
It will work.
my page file will have issue 'Cannot find name 'IAboutIdProps'' Could you please explain me why it works like that? Additional informationNo response ExampleNo response |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
Did you import the import { shops } from "@/app/constants/constants";
import { IAboutIdProps } from "@/app/types"; // location of the `types` file.
export default function AboutId({ params: { id } }: IAboutIdProps) {
const shopInfo = shops.find((shopInfo) => shopInfo.id === id);
return (
<h3>
Something about {shopInfo?.name || "This shop does not exist in DB"}
</h3>
);
} |
Beta Was this translation helpful? Give feedback.
-
This is an obscure TypeScript feature. If a file has no import/export, then it is not a module, so it becomes global. For example: // import type {GetServerSideProps} from 'next'
interface Foo {
bar(): void;
}
type Baz = {
fizz(): void;
}; As long as the top line is commented, Foo and Baz will be visible from other files. The moment you uncomment that, this becomes a module and both Foo, and Baz, become private instances of the module. Likewise, the moment this file does an This sort of reliance on global, or magically available, types, is anti-pattern that'll bring lots of chaos to your codebase. Avoid it. --isolatedModulesWhat is throwing me off here, is that This is what I'd expect: 'foo.ts' cannot be compiled under '--isolatedModules' because it is considered a global script file. Add an import, export, or an empty 'export {}' statement to make it a module.ts(1208) For a function foo(){} [email protected] (verified in 4.9.5 too)It might be a TS issue... now that I've downgraded from 5.x.x to 4.x.x, I see the error I'd expect: I'll go through the TS release logs and see if there's something mentioning this change in behaviour. For completeness sake here's the entire file from the screenshot: // import type {GetServerSideProps} from 'next'
interface Foo {
bar(): void;
}
type Baz = {
fizz(): void;
};
function foo() {} |
Beta Was this translation helpful? Give feedback.
This is an obscure TypeScript feature. If a file has no import/export, then it is not a module, so it becomes global.
For example:
As long as the top line is commented, Foo and Baz will be visible from other files. The moment you uncomment that, this becomes a module and both Foo, and Baz, become private instances of the module. Likewise, the moment this file does an
export
, it turns into a module too.This sort of reliance on global, or magically available, types, is anti-pattern that'll bring lots of chaos to your codebase. Avoid it.
--isolatedModules