Home > Back-end >  typescript getting intellisense to work without classes
typescript getting intellisense to work without classes

Time:10-14

New to typescript here, trying to convert this simple js to ts.

Here's my js:

Item = {}

Item.buy = function (id) {}
Item.sell = function (id) {}

I don't want to use class and I just want to use Item as a namespace.

I'm trying to get it so that when I type Item. it autocompletes buy or sell. I tried:

namespace Item {}
interface Item {}

Item:Item = {}

All of these give me errors.

Based on Phil's answer, this is closer to what I'm looking for:

interface Item {}
const Item: Item = {};

interface Item {
  buy?: Function
}
Item.buy = function () {
  Item.render()
  return "bought"
}

interface Item {
  sell?: Function
}
Item.sell = function () {
  Item.render()
  return "sold"
}

interface Item {
  render?: Function
}
Item.render = function () {
    return 1
}

Unfortunately this errors.

CodePudding user response:

Define an interface with the properties and method types

interface BuyAndSell {
  buy: (id: unknown) => void;  // you should use something more specific
  sell: (id: unknown) => void; // than "unknown"
}

then use that when declaring the implementation

const item: BuyAndSell = {
  buy: function (id) {},
  sell: function (id) {},
};

You can always create the functions at any time before creating the BuyAndSell implementation...

const buy: BuyAndSell["buy"] = (id) => {};
const sell: BuyAndSell["sell"] = (id) => {};

// or without explicit typings, eg
// const buy = (id: unknown) => {};

// and later...

const item: BuyAndSell = { buy, sell };
  • Related