DEV Community

John Peters
John Peters

Posted on • Updated on

Typescript Casting

Much has been written by Javascript folks concerning their dislike of the "new" keyword in Typescript. Here's an example of what they mean.

We don't need no stinkin' New in Typescript

      //implied new object, no "new" needed here
      let AJavaScriptObject = { SettingsGroupName: "TEST", Settings: [] };
      //return an object with key 'test' that returns the AJavaScriptObject ref.
      function AJavaScriptFunction() { return { test: AJavaScriptObject } }

      let makeTestVisible = AJavaScriptFunction();
      //ahh yes we can see the 'test' proptery key and its context.
      makeTestVisible.test.SettingsGroupName = "ok";
      //the settings property also visible
      makeTestVisible.test.Settings = null;
      //wait what's this?
      let temp2: SettingGroup = AJavaScriptObject;
Enter fullscreen mode Exit fullscreen mode

It's not apparent from the first few lines of code what type is being created. Until we get to the last line.. But, you say 'new implies type' I like "new" because it's synonymous with a type.

There's an alternative, which avoids using "new", to morph a JavaScript object into a Typescript "type" object.

The Typescript Pattern for Casting

//this is a cast of the AJavaScriptObject!
let temp2: SettingGroup = AJavaScriptObject;
Enter fullscreen mode Exit fullscreen mode

Where the SettingGroup class/type is defined as follows:

export class SettingGroup {
   SettingsGroupName: string;
   Settings: Array<Setting>;
}
Enter fullscreen mode Exit fullscreen mode

What did the cast do? Well it allowed Typescript to use it's tooling to determine property type safety. If an attempt to cast something does not have all of the required properties, a design time error is seen. This prevents the user from compiling the code.

No big deal right?

      let temp2: SettingGroup = AJavaScriptObject;
      temp2.temp = "test"
Enter fullscreen mode Exit fullscreen mode

Depends on how much you like "strict mode" the 2nd line above shows a development time error in that the property temp does not exist on the SettingGroup type. No arbitrary property type or function type assignments are allowed when casting to a type.

In a future article we'll show how to get rid of typing in Typescript when ever you want to "avoid" the rules.

JWP2020

Top comments (0)