更新
這里是D3 的API的鏈接,以及一個代碼框供您動手操作型別。selection.data
目標是擁有一個通用型別的介面,并在實作期間傳遞一個屬性鍵(也是通用的)來參考給定型別上的給定鍵。
我似乎無法正確輸入。
編碼
我有一個具有兩個屬性的介面:
interface Props<T, K extends keyof T> {
data: T[]
dataKey: K
}
我嘗試在我的函式中使用它:
const Heatmap = <T, K extends keyof T>({ data, dataKey }: Props<T, K>) => {
…
const svg = d3.select.<some other chained fns>
// then later
svg
.append(‘g’)
.selectAll(‘rect’)
.data<T>(d => d[dataKey]) // problem code
}
編譯器在資料回呼下抱怨:
Argument of type '(this: SVGGElement, d: T) => T[K]' is not assignable to parameter of type 'T[] | Iterable<T> | ValueFn<SVGGElement, T, T[] | Iterable<T>>'.
Type '(this: SVGGElement, d: T) => T[K]' is not assignable to type 'ValueFn<SVGGElement, T, T[] | Iterable<T>>'.
Type 'T[K]' is not assignable to type 'T[] | Iterable<T>'.
Type 'T[keyof T]' is not assignable to type 'T[] | Iterable<T>'.
Type 'T[string] | T[number] | T[symbol]' is not assignable to type 'T[] | Iterable<T>'.
Type 'T[string]' is not assignable to type 'T[] | Iterable<T>'.
Type 'T[string]' is not assignable to type 'T[]'.
Type 'T[keyof T]' is not assignable to type 'T[]'.
Type 'T[K]' is not assignable to type 'T[]'.
Type 'T[keyof T]' is not assignable to type 'T[]'.
Type 'T[string] | T[number] | T[symbol]' is not assignable to type 'T[]'.
Type 'T[string]' is not assignable to type 'T[]'.ts(2345)
在 vanilla js 中,資料回呼如下所示:
data(d => d.<key>)
我已經看遍了,無法將它拼湊起來。我使用 Record 實用程式擺弄了映射型別、索引型別,但我無法使其作業。我還嘗試了可選的關鍵引數回呼。似乎沒有什么可以平息tsc的。我在這里想念什么?為什么這不像我寫的那樣作業?
FWIW,我在這里的打字稿代碼確實在瀏覽器中作業,但tsc不會編譯
TIA
uj5u.com熱心網友回復:
更新 下面的解決方案確實滿足了編譯器,但只是表面上。我發現從那時起,打字稿就假定我在傳遞一個字串并且抱怨了很多。
最后的修復(到目前為止)是使用可選的key ValueFn. 宣告檔案不是很有幫助,但本質上,我能夠將.data()呼叫更改為:
.data(data, () => xKey as string)
這僅適用于我使用泛型并將密鑰作為道具傳遞給反應組件,但也許這會幫助某人沿著他們的旅程。
下面過時的解決方案
在這里找到了答案。它所需要的只是回傳一個字串,à la:
data(d => String(d[dataKey]))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/471085.html
上一篇:D3樹子節點的分頁
下一篇:錯誤型別引數分配的錯誤
