我正在嘗試在反應中動態呈現表格。通用屬性將確保動態索引資料陣列的元素(至少我是這樣)。我還希望只能將 T 型別的鍵傳遞給 columns 引數。因此,在這里擺脫泛型不是一個選擇。我還使用了 Extract 型別來分別呈現列,但排除它沒有區別。
function Table<T, Key extends keyof T>({
data,
columns,
}: {
data: T[];
columns: Extract<Key, string>[];
}) {
return (
<div>
{data.map((row) => (
<tr>
{columns.map((col) => (
<td>{row[col]}</td> //this is where the error appears
))}
</tr>
))}
</div>
);
}
這將產生以下錯誤:
Type 'T[Extract<Key, string>]' is not assignable to type 'ReactNode'.
Type 'T[Extract<keyof T, string>]' is not assignable to type 'ReactNode'.
Type 'T[string]' is not assignable to type 'ReactNode'.
Type 'T[string]' is not assignable to type 'ReactPortal'.
Type 'T[Extract<keyof T, string>]' is not assignable to type 'ReactPortal'.
Type 'T[Extract<Key, string>]' is not assignable to type 'ReactPortal'.
Type 'T[Extract<keyof T, string>]' is not assignable to type 'ReactPortal'.
Type 'T[string]' is not assignable to type 'ReactPortal'.ts(2322)
為了隔離錯誤,我嘗試使用簡單的動態索引和通用約束來重現錯誤:
function getKeyOfT<T, Key extends keyof T>(array: T[], key: Key) {
return array[key];
}
產生以下錯誤:
Type 'keyof T' cannot be used to index type 'T[]'.ts(2536)
我已經看過幾個答案,但它們似乎有所不同,他們的解決方案似乎沒有涵蓋我的問題:
- 型別 '"test"' 不能用于索引型別 'T'
- 型別 'K' 不能用于索引型別 '{ [key in keyof K]: V; }'.ts(2536)
- 型別 '1' 不可分配給型別 'T[Extract<keyof T, string>]'
正如他們中的一些人所建議的那樣,斷言型別應該可以解決問題。但是,在這種情況下,這似乎是多余的:
function getElementOfArray<T, Key extends keyof T>(array: T[], key: Key) {
return array[key as keyof T];
}
uj5u.com熱心網友回復:
當您嘗試隔離錯誤時,錯誤訊息已更改,因為它是一個不同的錯誤。
要解決您的原始錯誤:
Type 'T[Extract<Key, string>]' is not assignable to type 'ReactNode'
這只是意味著 TypeScript 不知道里面是什么型別的內容,T但它期望可以分配給ReactNode.
我會嘗試將您的函式的定義修改為:
function Table<T extends Record<string, ReactNode>, Key extends keyof T>({
data,
columns,
}: {
data: T[];
columns: Extract<Key, string>[];
}) {
return (
<div>
{data.map((row) => (
<tr>
{columns.map((col) => (
<td>{row[col]}</td> //this is where the error appears
))}
</tr>
))}
</div>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/497073.html
