我通過 API 獲取產品資料,資料嵌套很深,屬性可能會根據產品定義而變化。我是否需要完整輸入產品資料才能正確使用打字稿?或者您將如何處理前端中深度嵌套的資料?
ts游樂場
const product = {
id: 1,
colors: ["red", "green"],
comments: null,
variants: [
{
id: 1,
name: "t-shirt",
comments: null,
material: [
{
id: 1,
name: "cotton",
comments: ["Hello World"],
}
]
}
]
}
function getProduct<T>(product: T) {
return product
}
型別“T”上不存在屬性“變體”。
function setProductFirstVariantComment<T>(product: T, comment: string) {
product.variants[0].comments = [comment] // TS ERROR
return product
}
uj5u.com熱心網友回復:
Typescript 是一種型別嚴格的語言,因此您需要定義型別以映射到您的資料。
沒有型別,編譯器無法理解您參考的型別/資料。在您的情況下,product是泛型型別T,但編譯器不知道T您的背景關系中是什么,因為您從未在任何地方定義它。
您應該使用正確的型別映射您的資料,如下所示
type Material = {
id: number,
name: string,
comments: string[] | null,
}
type Variant = {
id: number,
name: string,
comments: string[] | null,
material: Material[]
}
type Product = {
id: number,
colors: string[],
comments: string[] | null,
variants: Variant[]
}
const productData: Product = {
id: 1,
colors: ["red", "green"],
comments: null,
variants: [
{
id: 1,
name: "t-shirt",
comments: null,
material: [
{
id: 1,
name: "cotton",
comments: ["Hello World"],
}
]
}
]
}
function getProduct<T>(product: T) {
return product
}
//define T which extends Product type
function setProductFirstVariantComment<T extends Product>(product: T, comment: string) {
product.variants[0].comments = [comment]
return product
}
setProductFirstVariantComment(productData, "new")
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/497076.html
標籤:打字稿
