我试图为我的项目定义类型,以便有一个通用的方法,同时能够缩小工作流中对象的特定属性.
satisfies
运算符似乎正是我所需要的,因为我可以在对象上使用泛型类型,并保持一个强的类型安全性,同时避免过多的样板代码来缩小类型.
但我在使用可选属性时遇到了困难,因为它们不会作为选项出现在自动完成中,并且我得到了一个IDE错误.
const formatterFunctions = {
foo: () => (true),
bar: undefined,
} as const
type FormatterFunctionsKeys = keyof typeof formatterFunctions
type MyObj = {
type: 'normal' | 'function',
message: string,
formatter?: typeof formatterFunctions[FormatterFunctionsKeys]
};
const objArray = {
foo: { type: 'function', message: 'someMessage', formatter: formatterFunctions.foo},
bar: {type: 'normal', message: 'barMessage'}
} satisfies {[K in FormatterFunctionsKeys]: MyObj}
for (const [key, entry] of Object.entries(objArray)) {
entry.formatter // <= error here 'formatter' doesn't appear in the autocomplete, and typing it manually creates an error. The only property are 'type' and 'message'.
}
TS错误消息:
Property 'formatter' does not exist on type '{ type: "function"; message: string; formatter: () => boolean; } | { type: "normal"; message: string; }'.
你能帮我找出我定义类型的方式有什么问题吗?
我的目标是让自动补全和正确的打字,同时仍然使用satisfies
.
精确度:代码是我的更复杂 case 的一个例子.但MyObj对象可以是类型:‘Normal’,并且具有格式化程序功能.