Skip to content

Commit d977984

Browse files
committed
Updated FAQ (markdown)
1 parent e966c63 commit d977984

File tree

1 file changed

+39
-2
lines changed

1 file changed

+39
-2
lines changed

FAQ.md

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1452,10 +1452,47 @@ See [#1617](https://github.com/Microsoft/TypeScript/issues/1617) for this and ot
14521452
14531453
### What's the difference between `declare class` and `interface`?
14541454
1455-
TODO: Write up common symptoms of `declare class` / `interface` confusion.
1455+
### What's the difference between `declare class` and `interface`?
1456+
1457+
`interface` describes an instance shape only. It does not declare any value, constructor, or inheritance target at runtime.
1458+
1459+
`declare class` describes an existing class value and its instance shape. It may be used when a constructor function with that name exists at runtime, but its implementation is provided elsewhere.
1460+
1461+
This affects which class relationships are meaningful:
1462+
1463+
* `implements` checks that a class's instance shape matches the type
1464+
* `extends` requires a real base class value at runtime
1465+
1466+
```ts
1467+
interface Shape {
1468+
area(): number;
1469+
}
1470+
1471+
declare class BaseShape {
1472+
area(): number;
1473+
}
1474+
1475+
class A implements Shape {
1476+
area() { return 0; }
1477+
}
1478+
1479+
class B extends BaseShape {
1480+
}
1481+
```
1482+
1483+
In the example above, `A` is only checked structurally. `B` inherits from `BaseShape`, so `BaseShape` must exist at runtime.
1484+
1485+
Common symptoms of confusion:
1486+
1487+
* Using `declare class` where only an object shape exists: `extends` compiles, but the emitted inheritance code fails at runtime
1488+
* Using `interface` where an existing class should have been described: `implements` works, but there is no inherited behavior, and runtime checks like `instanceof` do not apply
1489+
1490+
Rule of thumb:
14561491
1457-
See http://stackoverflow.com/a/14348084/1704166
1492+
* Use `interface` for "objects with these members"
1493+
* Use `declare class` for "this constructor exists at runtime"
14581494
1495+
See also [this StackOverflow answer](http://stackoverflow.com/a/14348084/1704166).
14591496
14601497
### What does it mean for an interface to extend a class?
14611498

0 commit comments

Comments
 (0)