[英]TypeScript generic default type vs Contextual Typing
在 TypeScript 中,我們有Contextual Typing ,當沒有定義泛型類型時,TypeScript 將嘗試從返回值推斷出正確的類型。
在大多數情況下,它工作正常。 但有時它會變得很奇怪。 就我而言,當 function 參數未定義時,有時不使用通用默認類型,這不是預期的。
type State = { count: number }
declare function simple<T = State>(second?: T): T;
const { count: countA } = simple()
// in 4.0+ => countA: number
// in 3.9 => countA: any;
declare function complex<M, T = State>(first: M, second?: T): T;
const { count: countB } = complex(1)
// countB: any;
我想問一下,這是一個 TypeScript 錯誤,還是有某種優先級來確定從哪個類型推斷,返回類型或通用默認類型?
這是一個 TypeScript 錯誤,還是有某種優先級來確定從哪個類型推斷,返回類型或通用默認類型?
這對我來說似乎是一個帶有解構分配的 TS 錯誤。 const {b} = fn();
應該等價於const tmp = fn(); const {b} = tmp
const tmp = fn(); const {b} = tmp
或const b = fn().b
。 我完全不知道為什么把它寫成const {b} = fn()
會破壞推斷的類型。
type State = { count: number }
declare function complex<M, T = State>(first: M, second?: T): T;
const { count: countB } = complex(1) // FAILS
const state = complex(2); // works!
const {count: countC} = state;
const countD = complex(3).count; // works!
let tmp;
const { count: countE } = tmp = complex(4); // works!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.