Home > OS >  How come TypeScript can't see the fields of a type in a function parameter?
How come TypeScript can't see the fields of a type in a function parameter?

Time:12-21

I have a packages object, to which I add items of the Package type ( enter image description here

While it does show what callback's fields are if I type it as a function:

enter image description here

I won't get this information unless I know that callback needs to be a function which has an object with these keys as its argument.

How can I let someone that's using addPackage know that callback is a function with the fields of Callback?

The shape of my object (in plain JS) should end up looking like this:

{
  123: {
    callback: () => {
      //Whatever was added as a callback from `addPackage`.
      //Naturally, we are also given access to the parameters 'source' and 'types' here.
    }

  }
}

As a side-note, TS borks even further when I start typing callbacks's properties. It doesn't see them anymore, so, there's no highlighting:

enter image description here

I'm open to heavy criticism, as I'm learning TS. If you have a better idea on how to write this, I'm all ears and I appreciate it a lot.

CodePudding user response:

Try this code: https://stackblitz.com/edit/typescript-7znmjv

Inlined here:

type Callback = (callbackParams: {
  source: string;
  types: string[];
  meta?: {};
}) => void;

const packages = {};

const addPackage = (id: string, callback: Callback) => {
  packages[id] = callback;
};

addPackage('123', (params: { source: string; types: string[]; meta?: {} }) => {
  console.log(params.source);
});

packages['123']({ source: 'hey', types: [] });
  • Related