4

I want to extend string with a method that needs an enumeration to be passed. How do I import that enum into the declaration file?

CapitalizationStyle.tsx:

export enum CapitalizationStyle {
    None = 0,
    Lowercase = 1,
    Word = 2
}

StringExtensions.d.ts:

import { CapitalizationStyle } from "Utils/CapitalizationStyle"; //This line breaks everything.

declare interface String {
    applyCapitalizationStyle(this: string, style: CapitalizationStyle): string;
}

The import breaks the interface declaration, like if the declaration does not exist anymore. All extension implementations of the String class become invalid as soon as I add the import:

StringExtensions.tsx:

enter image description here

Minimal reproducible example project: https://wetransfer.com/downloads/d1a707c0ac734985b877058967c35a6820171212143715/410f48

2
  • Can you more precisely explain "breaks everything"? Do you have a TSLint error? Is it by change "TS1192: <path> has no default export"? Commented Dec 7, 2017 at 18:39
  • I have added some more details in my original post to clarify this. This import breaks the whole file, like if none of the declarations (StringExtensions.d.ts) exist anymore, make all implementations invalid (StringExtension.tsx) Commented Dec 9, 2017 at 3:17

2 Answers 2

2

Since you don't have a default export from that module, you need to wrap it in {}:

import { CapitalizationStyle } from "Utils/CapitalizationStyle";
Sign up to request clarification or add additional context in comments.

6 Comments

It seems that you were 10 secs faster than me! Bravo, +1!
Thank you, but this is not the issue. I have added some more details in my original post. The problem is not with the import itself, but that it breaks the declaration completely.
@sixtstorm1 Thanks for adding detail. Can you make a plunkr?
I have tried to make a plunkr but after fiddling around did not find how to make it work. I have added a link to a minimal reproducible example in my original post. The build will fail with Property 'applyCapitalizationStyle' does not exist on type 'String'. Remove the import from the d.ts (and remove the enum from the method signature), and it will build correctly.
Well StringExtensions is used pretty much everywhere, I'm just adding methods to the prototype, so I can do something like: var str1 = 'joHn dOE'; console.log(str1.applyCapitalizationStyle(CapitalizationStyle.Word)); //Outputs 'John Doe'
|
0

Try wrapping in curly braces, like this:

import {CapitalizationStyle} from "Utils/CapitalizationStyle";

since you don't default-export your custom enumeration.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.