我有这个TS代码:
type MyFunctions = {
play(): void
pause(args: { reset: boolean }): void
stop(args: { restart: boolean }): void
}
type AuthStruct = {
[K in keyof MyFunctions]: {
requiresAuth: boolean
}
}
const auth = {
play: {
requiresAuth: true
},
pause: {
requiresAuth: true
},
stop: {
requiresAuth: false
}
} as const satisfies AuthStruct
type Auth = typeof auth
type FunctionParameters<K extends keyof MyFunctions> = Parameters<
MyFunctions[K]
>[0] extends undefined
? never
: Parameters<MyFunctions[K]>[0]
type Data<K extends keyof MyFunctions> = (FunctionParameters<K> extends never
? {}
: FunctionParameters<K>
) & (
Auth[K] extends { requiresAuth: true }
? { token: string }
: {}
)
function runFunction<F extends keyof MyFunctions>(
func: F,
data: Data<F>
) {
if(auth[func].requiresAuth) {
data.token // Should work
}
}
我假设在运行条件判断if(auth[func].requiresAuth)
之后,编译器会理解data
有一个requiresAuth
属性.但不幸的是它不起作用.此外,我甚至不能强迫编译器接受data
具有token
属性,比如:data.token!
. 如何解决这个问题?