简体   繁体   中英

How to iterate object knowing value type in TypeScript?

I have a dictionary of UI changes that come from the API:

interface UIChangesDictionary {
    christmasTreeCount: number;
    greeting: string;
    isDarkMode: boolean;
}

Let's use static object to make things easier:

const changes: UIChangesDictionary = {
    christmasTreeCount: 14,
    greeting: "Ho ho ho",
    isDarkMode: true,
};

Now, in my API handler, I'd like to iterate over these changes and apply appropriate UI changes:

Object.entries(changes).forEach(
    ([ property, value ]) => {
        switch (property) {
            case "christmasTreeCount":
                // value should be number
                break;
            case "greeting":
                // value should be string
                break;
            case "isDarkMode":
                // value should be boolean
                break;
        }
    }
);

Unfortunately, the value is always any . I thought Object.entries() would be able to infer the type properly, but it can't.

How would I implement it to have value use a type from its interface?

  • You can use a type assertion or type graud.
Object.entries(changes).forEach(([property, value]) => {
  const change = value as UIChangesDictionary;
  switch (property) {
    case 'christmasTreeCount':
      // value should be number
      console.log(change);
      break;
    case 'greeting':
      console.log(change);
      break;
    case 'isDarkMode':
      console.log(change);
      break;
  }
});

or type graud.

Object.entries(changes).forEach(([property, value]) => {
  switch (property) {
    case 'christmasTreeCount':
      if (typeof value === 'number') {
        const count = value;
        console.log(count);
      }
      break;
    case 'greeting':
      break;
    case 'isDarkMode':
      break;
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM