Nikitha
Nikitha

Reputation: 27

TypeScript - Using predefined names for custom class names

Can we use predefined names from TypeScript for naming custom classes/interfaces? Can there be a use case that can lead to an error if a custom class name conflicts with a predefined name from TypeScript?

For example - Can I create a custom class called RequestInfo while TypeScript already has a RequestInfo type -> type RequestInfo = Request | string;?

Upvotes: 2

Views: 638

Answers (1)

FloWy
FloWy

Reputation: 984

You cannot use any predefined name from TypeScript as a custom class/interface/type. The reason being is that a class declaration creates a constructor function as well as a type definition. That means I can do something like this:

class Hero {}
const myHero: Hero = new Hero();
const somethingElse: Hero & string = '';

Therefore, the TypeScript compiler issues an error, when you try to redefine a predefined type because a type is in general generated for a class.

However, if you want to have more than one interface declaration within your module, TypeScript will use the declaration merging concept which just merges both interfaces into one.

interface Hero { x!: number; }
interface Hero { y!: number; }

Upvotes: 1

Related Questions