[Typescript] Declaration Merging

Stacking multiple things on an identifier


interface Fruit {
  name: string
  mass: number
  color: string
}
 
const Fruit = {
  name: "banana",
  color: "yellow",
  mass: 183,
}
 
export { Fruit }

You can also stack namespace:

class Fruit {
  static createBanana(): Fruit {
    return { name: "banana", color: "yellow", mass: 183 }
  }
}
 
// the namespace
namespace Fruit {
  function createFruit(): Fruit {
    // the type
    return Fruit.createBanana() // the class
  }
}
 
interface Fruit {
  name: string
  mass: number
  color: string
}
 
export { Fruit }

I propose that in the situation above, we have one identifier that’s three things in one:

  • a value (class)
  • a type
  • a namespace

Proving this hypothesis will be easier if we have some way to tell what’s on an identifier

This works fine:

const is_a_value = 4
type is_a_type = {}
namespace is_a_namespace {
  const foo = 17
}
 
// how to test for a value
const x = is_a_value // the value position (RHS of =).
 
// how to test for a type
const y: is_a_type = {} // the type position (LHS of = ).
 
// how to test for a namespace (hover over is_a_namespace symbol)
is_a_namespace

But this will fail:

basiclly it tells that 

  • You cannot use a type on Right side of = (you cannot use type as a value)
  • You cannot use value on the Left side of = (you cannot use value as type)

The namespace test is a bit self-explanatory, so we’ve left that out, but hopefully this is convincing enough

 

posted @ 2022-08-08 18:30  Zhentiw  阅读(19)  评论(0编辑  收藏  举报