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



I have a packages object, to which I add items of the Package type (
Plain JS "what I’m trying to achieve" also Playground link), as such:

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

interface Package {
  callback: Callback;

const packages: { [packageId: string]: Package } = {};

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

If I were to start typing addPackage('somePackage', TS will tell me that packageId is of type string, but all it can tell me about callback is that it’s of type Callback:

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.


Try this code:

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?: {} }) => {

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

Answered By – Janos Vinceller

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More