键入 Vue 函数的更好方法?

Better way to Type a Vue function?

大家下午好,

我整个上午都在为在我的 Vue 应用程序中输入 ThemeSwitcher 函数而苦恼。如果能就此问题提供一些见解,我将不胜感激。

这是我的代码:

// 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);

这是我的错误:

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'.
};

我最终通过在界面中添加以下行来修复它:

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

我的问题是:这是正确的方法还是我可以用更好的方法来完成?

提前致谢。

您还可以将主题 属性 定义为类型 (type ThemeProperty = 'theme'|'isBrowserThemeDark'),然后使用 Record 实用程序创建 Theme 类型:


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);