List

  • 关于 Interface 与 Type
  • 全局变量声明

关于 Interface 与 Type

Type aliases and interfaces are very similar, and in many cases you can choose between them freely. Almost all features of an interface are available in type, the key distinction is that a type cannot be re-opened to add new properties vs an interface which is always extendable.

  1. // Extending an interface
  2. interface Animal {
  3. name: string
  4. }
  5. interface Bear extends Animal {
  6. honey: boolean
  7. }
  8. const bear = getBear()
  9. bear.name
  10. bear.honey
  11. // Adding new fields to an existing interface
  12. interface Window {
  13. title: string
  14. }
  15. interface Window {
  16. ts: TypeScriptAPI
  17. }
  18. const src = 'const a = "Hello World"';
  19. window.ts.transpileModule(src, {});
  1. // Extending a type via intersections
  2. type Animal = {
  3. name: string
  4. }
  5. type Bear = Animal & {
  6. honey: Boolean
  7. }
  8. const bear = getBear();
  9. bear.name;
  10. bear.honey;
  11. // A type cannot be changed after being created
  12. type Window = {
  13. title: string
  14. }
  15. type Window = {
  16. ts: TypeScriptAPI
  17. }
  18. // Error: Duplicate identifier 'Window'.

参考链接

Typescript 中的 interface 和 type 到底有什么区别

全局变量声明

  1. declare var chrome: any;