-
Notifications
You must be signed in to change notification settings - Fork 12.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Cannot access name of function or class in a type-safe way #2076
Comments
It is easy to fix. interface Function {
name: string;
}
// Using it
function f(): string { return f.name; } The 'name' property is part of ES6 that's why you don't see it in lib.d.ts. I think it will be declared in lib.es6.d.ts and you need to use ES6 generation option. |
Thanks for the quick answer, I didn't realize I could extend Function. Indeed, compiling for ES6 works without any added declaration, and adding the interface declaration works for ES5. And it also gives access to the class name as |
Interfaces can be extended. |
I have class that looks like this: class Iterator {
protected position: Position;
constructor(position: Position) {
this.position = position;
}
toString(): string {
return this.constructor.name;
}
} When I compile, I get the following error: |
I suspect you have put your code augmenting the |
yes at the end of the file I wrote: export = Iterator; Could you point me to a way I should rewrite my code? Thank you so much for the support @danquirk |
@wcandillon put your extensions in a .d.ts that exists in the global scope (where the existing Function definition from lib.d.ts is) and reference that. So: ext.d.ts: interface Function {
name: string
} iterator.ts: /// <reference path='ext.d.ts'/>
class Iterator {
protected position: Position;
constructor(position: Position) {
this.position = position;
}
toString(): string {
return this.constructor.name;
}
}
export = Iterator; |
hi, getContact():any { When i compile, I get the following error in gulp: |
@yagobilel please post questions on Stack Overflow |
@wcandillon You can also trick TypeScript by casting Example: toString(): string {
return (<any>this).constructor.name;
} |
The question is: why it's not part of TypeScript? Doesn't Function has .name in specification? |
The |
True. Thank you! |
The property
name
of function does not seem to be available in Typescript:I can declare an interface but it requires a cast:
Is there a better way? Shouldn't Typescript know about the predefined properties of functions?
While I'm at it, the same issue comes up with classes: the name of the constructor is the name of the class, so in plain Javascript you could get the name as above, but it does not work in Typescript:
Here the above solution does not even work, since A is considered as the class, not the constructor function...
The text was updated successfully, but these errors were encountered: