2 回答

TA貢獻(xiàn)1757條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以使用函數(shù)重載:
interface Foo {
bar: number,
baz: number,
}
interface FooEnabled extends Foo {
enabled: true,
}
interface Result {
result: number;
}
interface IsEqual extends Result {
isEqual: boolean
}
function foo(foo: FooEnabled): IsEqual;
function foo<T extends Foo>(foo: T): Result;
function foo({bar, baz, enabled}: FooEnabled): Result | IsEqual {
const result = baz + bar;
if (enabled) {
return {
result,
isEqual: bar === baz,
}
}
return {
result,
}
}
const {result} = foo({
bar: 5,
baz: 5,
});
const {result: anotherOneResult, isEqual} = foo({
bar: 5,
baz: 5,
enabled: true,
})

TA貢獻(xiàn)1911條經(jīng)驗(yàn) 獲得超7個(gè)贊
您可以在打字稿中為函數(shù)定義多個(gè)返回類型。對(duì)于您的示例,您可以這樣做:
function foo({bar, baz,enabled=false}: Foo): Result | AnotherResult { return (enabled==true)?{result: bar + baz, isEqual: true}: {result: bar + baz} ; }
添加回答
舉報(bào)