Dreams
Dreams

Reputation: 8506

How to define new URL when using typescript

Below is my code

const url: any = new URL((global as any).window.location);

However, typescript says can not find name URL.

How can I fix it?

Upvotes: 1

Views: 2806

Answers (1)

Josh
Josh

Reputation: 3440

Short version: The URL type is declared in the "DOM" lib. Add that to the "lib" section of your tsconfig.json:

{
    "compilerOptions": {
        "lib": ["dom"],
    }
}

(if you already have other entries under "lib", that's fine too - just add "dom" to the array)

Long version:

The "lib" compiler option indicates which groups of built-in type definitions TypeScript should include. For example, you may include the "es2015" group to include type definitions for features added in ES2015.

The "dom" lib option refers to types that exist in browser environments but not Node environments. The URL class is an example of that, so it's declared in the "dom" types.

Note that TypeScript includes the "dom" types by default. I'm guessing you've overridden the list to something else, and aren't including them in yours.

For more info, see:

Upvotes: 2

Related Questions