【发布时间】:2021-06-10 18:25:18
【问题描述】:
我有一个设置对象,想为这样的函数提供单个键值对:
const settings = {
time1: 40 * 60 * 60,
time2: 10 * 60 * 60,
breaks: [
{ limit: 6 * 60 * 60, length: 30 * 60 },
{ limit: 9 * 60 * 60, length: 15 * 60 },
],
}
// works
function changeSetting1<T extends keyof typeof settings>(details: {key: T, value: typeof settings[T]}): void {
//
}
// doesn't work
type func_details = <T extends keyof typeof settings>{key: T, value: typeof settings[T]}
function changeSetting2(details: func_details): void {
changeSetting1({key: "time1", value: 8 * 60 * 60})
changeSetting2({key: "time1", value: 8 * 60 * 60})
虽然当我直接在函数中键入时它似乎可以工作,但 TypeScript 抱怨说,当我第一次定义类型 func_details 时预期会有一个 (。这样做的正确语法是什么?
【问题讨论】:
标签: typescript