各位好心人,下午好
我整個早上都在為在我的 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,
我的問題是:這是正確的方法還是我可以以更好的方式做到這一點?
先感謝您。
uj5u.com熱心網友回復:
您還可以將主題屬性定義為 type ( type ThemeProperty = 'theme'|'isBrowserThemeDark'),然后使用Record實用程式創建Themetype :
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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/486812.html
