Home > Back-end >  Better way to Type a Vue function?
Better way to Type a Vue function?

Time:06-05

Good afternoon good people,

I've been wrestling for the entire morning with Typing a ThemeSwitcher function in my Vue Application. I'd would be grateful for some insight on this issue.

This is my code:

// Typing of state and functions
type ThemeValue = 'dark' | 'light'

interface Theme {
  [key: string]: string | number | boolean,
  theme: string,
  isBrowserThemeDark: boolean
}

const state: Theme = reactive({
  theme: '',
  isBrowserThemeDark: window.matchMedia('(prefers-color-scheme: dark)').matches
})

provide('Theme State', toRefs(state))


const updateState =  (property:keyof(typeof state), value: ThemeValue): void => {
    state[property] = value
};

provide('Update Theme State', updateState);

This was my error:

const updateState =  (property:keyof(typeof state), value: ThemeValue): void => {
    state[property] = value 
    // The TS error I was getting, was the following: 
    // Impossible to assign the type 'string' to type 'never'.
};

I ended up fixing it by adding the following line in the Interface:

[key: string]: string | number | boolean,

My question is: Was this the right aproach or could I have done it in a better way?

Thank you in advance.

CodePudding user response:

You could also define the theme property as type (type ThemeProperty = 'theme'|'isBrowserThemeDark'), then use Record utility to create the Theme type :


type ThemeValue = 'dark' | 'light'
type ThemeProperty = 'theme'|'isBrowserThemeDark'

type Theme = Record<ThemeProperty, string | boolean>

const state = reactive<Theme>({

  theme: '',
  isBrowserThemeDark: window.matchMedia('(prefers-color-scheme: dark)').matches
})

provide('Theme State', toRefs(state))

const updateState =  (property:ThemeProperty, value: ThemeValue): void => {
    state[property] = value
};

provide('Update Theme State', updateState);

  • Related