Home > Mobile >  Type '(foo: SomeType) => "a" | "b"' is not assignable to type '
Type '(foo: SomeType) => "a" | "b"' is not assignable to type '

Time:10-22

I know there's a better way but I'm trying to implement a simple next theme function.

export type Theme = "light" | "dark";

export const nextTheme: Theme = (current: Theme) => {
  switch (current) {
    case "light": {
      return "dark";
    }
    case "dark": {
      return "light";
    }
  }
};

And the error I'm getting is

Type '(current: Theme) => "light" | "dark"' is not assignable to type 'Theme'.

Type '(current: Theme) => "light" | "dark"' is not assignable to type '"dark"'.ts(2322)

I might be having one of those moments, but why wouldn't this be valid? Would it be better to use enums to keep track of the different themes?

CodePudding user response:

You have your return type in the wrong place, it should be after the parentheses:

export type Theme = "light" | "dark";

export const nextTheme = (current: Theme): Theme => {
  switch (current) {
    case "light": {
      return "dark";
    }
    case "dark": {
      return "light";
    }
  }
};
  • Related