2

I am building a project in Typescript using Atom as my text editor. I have atom-typescript installed, which is compiling my code to JavaScript automatically.

What I am attempting to do is define a new extension method on type string to determine if it is null or blank. I have a main file which exports a single function, and a mocha test attempting to verify it is all working. The issue I am running into is that mocha is throwing a type error:String.isNullOrEmpty is not a function

Here is my stringExtensions.ts:

interface StringConstructor {
  isNullOrEmpty(str: string): boolean;
}

String.isNullOrEmpty = function(str: string): boolean{
  return (!str || 0 === str.length);
}

In my main.ts I have the following code:

///<reference path="extensions/stringExtensions.ts"/>
export function checkForUpdate(){
  if(String.isNullOrEmpty(location)){
    /* Do Stuff */
  }

In main.spec.ts

import {checkForUpdate} from "../lib/update"
describe("test", ()=>{
  if("should do something", ()=>{
    checkForUpdate();
  })
})

If I copy my code from the extension file into the main file everything is working fine so I know this is a reference problem. Atom-typescript is throwing no errors, it is able to find the code just fine and everything looks good on its end.

What modifications do I need to make to have the reference work correctly. I am looking at the compiled JavaScript code and there is no import instruction from my reference command. Should there be?

1 Answer 1

1

The problem here is that typescript is able to find the isNullOrEmpty definition because of the triple slash reference. However, the execution is not reaching the point where the function is being bound to String. i.e the line of code

String.isNullOrEmpty = ...

is not being executed which is why String.isNullOrEmpty is undefined when you try to call the function. To fix this you can simply add

import './<path-to-file>/stringExtensions.ts'

to your main.ts. The import will execute the code in stringExtensions.ts and the function should be available inside your checkForUpdate function.

Sign up to request clarification or add additional context in comments.

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.