Chart.js自定义插件选项能否在TypeScript中设为必填键?
在React+TypeScript中让Chart.js自定义插件选项保持必填类型
问题背景
我在React与TypeScript环境中使用Chart.js,按照StackOverflow的方法在index.d.ts文件中定义了自定义插件的类型:
export type MyPluginOptions = { foo: string; bar: string; }; declare module 'chart.js' { interface PluginOptionsByType<TType extends ChartType> { myPlugin?: MyPluginOptions; } }
问题在于Chart.js会把这个类型包装在_DeepPartialObject<>中,导致foo和bar被自动转为可选属性,违背了我希望它们必填的需求。我觉得可以用TypeScript的Required<>来解决,但不知道具体怎么操作。
更多上下文
我定义的图表选项代码如下:
const myChartOptions: ChartOptions<'bar'> = { // 其他选项 plugins: { myPlugin: { foo: 'something', bar: 'something else', }, }, };
这里TypeScript允许foo和/或bar缺失。在编写插件逻辑时,我试过两种写法:
第一种是直接指定参数类型:
const myPlugin : Plugin<'bar'> = { id: 'my-plugin', afterDraw: function (chart, _args, options: MyPluginOptions) { if (options) { const x = options.foo; const y = options.bar; // 更多代码 } } };
这种写法虽然让TypeScript推断foo和bar存在,但也强制认为options一定存在,可能引发运行时问题。
第二种写法是从图表实例中获取选项并断言类型:
const myPlugin : Plugin<'bar'> = { id: 'my-plugin', afterDraw: function (chart) { const options = chart.plugins?.myPlugin as MyPluginOptions; if (options) { const x = options.foo; const y = options.bar; // 更多代码 } } };
这种写法基本能满足逻辑需求,但在设置图表选项时,TypeScript不会检查foo和bar是否必填。
已考虑的变通方案
- 将插件选项放在独立对象中,完全绕过Chart.js的类型系统
- 把
foo和bar视为可选属性,为未定义的情况设置默认行为(我觉得没必要,但怀疑这是Chart.js团队的设计意图)
希望得到更合适的推荐做法,尤其是如何让TypeScript在设置选项时就强制检查必填属性。
内容的提问来源于stack exchange,提问作者Milten
相关产品推荐
相关产品推荐

