我想定义一个类型Bar
,它是一个具有两个属性a
和foo
的对象。 属性a
的类型为A
或B
。属性foo
的类型取决于属性a
的类型。如果a
的类型为A
,则foo
的类型为(s: AA) => void
。如果a
的类型为B
,则foo
的类型为(s: BB) => void
。如何定义Bar
?
例如,假设type A = string
、type AA = string
、type B = number
和type 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
}
操场