Closed
Description
Search Terms
allowJs extends
inherit class method
Suggestion
When omitting type annotations in class methods, typescript will try to copy type information from base class or interface.
Use Cases
- Avoid repetition as repeated type information can be omitted in sub classes or classes implemented an interface.
- Simplify refactoring when changing interface one don't have to change
- Get type coverage faster when adding types to an existing JS project (this is my use case)
- Make it easier to enable
noImplicitAny
on existing code bases because less types are needed (this is my use case)
Examples
class BaseClass {
method(p1: number, p2: string): void {}
}
interface Iface {
otherMethod(p1: number, p2: string): void
}
class SubClass extends BaseClass implements Iface {
method(p1, p2) { // signature will be inherited from BaseClass
p1.substr(1, 2); // should fail because p1 is number
p2.toFixed(); // should fail because p1 is string
}
otherMethod(p1, p2) { // signature will be inherited from Iface
p1.substr(1, 2); // should fail because p1 is number
p2.toFixed(); // should fail because p1 is string
}
}
class BaseClass {
destruct(options: { a: number, b: string, c: number[] }): void;
}
class SubClass extends BaseClass {
destruct({ a, b }) {
// instead of destruct({ a, b }: { a: number, b: string }) {
a.substr(1, 2); // should fail because a is number
b.toFixed(); // should fail because c is string
}
}
class BaseClass {
/**
* @param {number} p1
* @param {string} p2
* @returns {void}
*/
method(p1, p2) {
// p1.substr(1, 2); // do fail because p1 is number
// p2.toFixed(); // do fail because p1 is string
}
}
class SubClass extends BaseClass {
method(p1, p2) {
p1.substr(1, 2); // should fail because p1 is number
p2.toFixed(); // should fail because p1 is string
// but it compiles fine, assuming p1 and p2 as any
}
}
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript / JavaScript code
- As it applies more types this could emit more errors.
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. new expression-level syntax)