打字稿 - 通过第二个属性类型推断属性类型



我想定义一个类型Bar,它是一个具有两个属性afoo的对象。 属性a的类型为AB。属性foo的类型取决于属性a的类型。如果a的类型为A,则foo的类型为(s: AA) => void。如果a的类型为B,则foo的类型为(s: BB) => void。如何定义Bar

例如,假设type A = stringtype AA = stringtype B = numbertype BB = number。我希望以下代码可以工作:

const f = ({ a, foo }: Bar): void => {
if (a === 'abc') {
foo('def')
}
}

和以下代码显示错误:

const f = ({ a, foo }: Bar): void => {
if (a === 'abc') {
foo(4)
}
}

您可以在Bar中使用联合类型,然后让函数像这样引用该类型

type Bar = {
a: string | number,
foo: (s: Bar['a']) => void
} 

操场

最新更新