如何在函式體內縮小泛型返回值的型別?

時間 2021-06-22 00:28:15

1樓:塔希

TS4.3 似乎對相關控制流的分析做了一些改進,嘗試了下似乎只在特定某些場景下有效,至少我隨便想的幾個用法無法正常工作

Announcing TypeScript 4.3 | TypeScript (microsoft.com)

最終答案:就是沒做

Relate control flow to conditional types in return types · Issue #33912 · microsoft/TypeScript (github.com)

還有這個

typescript - Implementing a generic function with a conditional return type - Stack Overflow

The underlying issue is that TypeScript's compiler does not narrow the type of a generic type variable via control flow analysis. When you check(typeof maybeNumber === "number"), the compiler can narrow thevalue

maybeNumbertonumber, but it does not narrow thetype parameter

Ttonumber.

Type narrowing forgotten inside function scope for CONST variables · Issue #34557 · microsoft/TypeScript (github.com)

Trade-offs in Control Flow Analysis · Issue #9998 · microsoft/TypeScript (github.com)

2樓:高山景行

type Key = 'p1' | 'p2'

type S = ;

p2: ;

};function TTT(p: ): S[T] ,p2:

const Test = TTT<'p1'>();

JS 建構函式返回值的問題

如果return的值是object,那麼就返回這個return的object,前面的this就都是無效的 如果return的值型別不是object,就還是返回this 搬運一下Annotated ES5 11.2.2 The new Operator The production NewExpres...

C 的函式返回值是如何構造的?

你如果是想問為什麼少輸出乙個new的話,那是因為F在隱式建立返回值物件的過程中,呼叫的是複製建構函式A const A 而不是預設的無參建構函式A 所以你自定義的無參建構函式A 並沒有捕獲到這次構造。include using namespace std struct A A A const A o...

為什麼不把要返回元素直接當成函式的返回值返回呢?

phoenix bool get elem elem get throw elem get bool 回字的四種寫法 iter get tuple get 想到再加 ant 有些時候乙個返回不夠用啊,函式中好幾個值需要傳出時只能通過引數傳遞實現,而不能簡單的通過函式返回值。當然,你也可以設計乙個資料...