[英]Typescript: Does parameter order affect type inference?
我有以下類型:
type State<C, S> = {
onEnter?: (context: C) => void;
onExit?: (context: C) => void;
transitions?: (context: C) => S | undefined;
};
class FSM<C, S extends Record<keyof S, State<C, keyof S>>> {
constructor(public readonly states: S, public readonly context: C) {
/* ... */
}
}
如果我像這樣實例化它們:
const context = { foo: "bar" };
const f = new FSM(
{
a: { transitions: c => "b" }, // ERROR: c is implicitly any
b: { transitions: c => "a" } // ERROR: c is implicitly any
},
context
);
編譯器抱怨c
是隱式any
並且它無法解析S
的類型(它出現為never
)。 顯式輸入c
解決問題,例如:
a: { transitions: (c:typeof context) => "b" },
b: { transitions: (c:typeof context) => "a" }
這是為什么? 它不應該能夠從FSM
構造函數的context
參數中推斷出C
嗎?
Wild Ass Guess : FSM
構造函數中參數的順序重要嗎? 是不是它首先嘗試解析states
類型並且還不知道context
的類型? 如果是這樣,有沒有辦法幫助編譯器“向前看”?
注意:我對此很難理解的另一件事是,如果我使用隨機類型顯式鍵入c
- 例如transitions: (c:number)=>"a";
編譯器抱怨c
與上下文類型不匹配。 所以編譯器知道c
是什么類型,但它需要我證明我也知道它?
如果有多個候選,參數順序可能對推理很重要,但事實並非如此。 您在這里真正想要的是使用上下文類型,這是編譯器根據要分配函數的位置的類型推斷參數類型的地方(在這種情況下)。
我不確定上下文類型何時放棄的機制,但如果分配給類型需要其他類型參數,它很有可能會停止工作。 一個簡單的解決方法是通過在與類型參數相交的參數類型中指定更簡單的類型來幫助上下文輸入。 這將確保我們仍然在S
捕獲傳入的實際類型,但我們為上下文類型提供了一個更簡單的路徑來推斷參數類型:
type State<C, S> = {
onEnter?: (context: C) => void;
onExit?: (context: C) => void;
transitions?: (context: C) => S | undefined;
};
class FSM<C, S extends Record<keyof S, State<C, keyof S>>> {
// Record<string, State<C, keyof S>> added for contextual typing
constructor(public readonly states: S & Record<string, State<C, keyof S>>, public readonly context: C) {
/* ... */
}
}
const context = { foo: "bar" };
const f = new FSM(
{
a: { transitions: (c) => c.foo != "" ? "a" : "b" },
b: { transitions: (c) => "a" },
c: { transitions: (c) => "d" }, // Error, d is not in the state keys
},
context
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.