gbieging
gbieging

Reputation: 318

use keyword as identifier in typescript

I'm trying to use the class keyword as a function identifier in a namespace like:

namespace X {
   export function class( ... ) { ... }
}

The namespace itself is extending a function (function X ( ... ) { ... }).

Is there any way this can be done?

Upvotes: 1

Views: 1786

Answers (3)

gbieging
gbieging

Reputation: 318

I found a workaround for this.

interface I {
   (foo: Bar): Baz
   class(foo: Bar): Baz
}

const X = (function (X: any) {
   X.class = function (foo: Bar) { ... }
   return <I>X
})(function (foo: Bar) { ... })

Upvotes: 1

Brendon Colburn
Brendon Colburn

Reputation: 1912

If what you're trying to do is name a method class this is a pretty big no no across programming languages. class is what you would call a reserved word: https://en.wikipedia.org/wiki/Reserved_word

You could call the method "Class" instead and will have better results I think.

Upvotes: 1

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 221402

There isn't a way to do this in TypeScript. You'd have to somehow declare a quoted name in a namespace, but there is no syntax for doing that. It's also impossible to declare a type named class, so you're blocked in two different ways.

You could write (<any>X)['class'] = class { ... } if you just needed this to be present at runtime and didn't need any type system features.

Upvotes: 5

Related Questions