[英]Infer typescript nested generic type
我正在嘗試執行以下操作:
function test<
Feature extends { shape: Geometry; properties: Properties },
Geometry extends geojson.Geometry,
Properties extends {}
>() {
const addFeature = (feature: Feature) => {
switch (feature.shape.type) {
case "Point":
break;
}
};
return {
addFeature,
};
}
test<{ shape: GeoJSON.Polygon; properties: {} }, GeoJSON.Polygon, {}>();
有什么辦法不需要傳入第二個泛型和第三個泛型? 我希望能夠做到這一點:
test<{ shape: GeoJSON.Polygon; properties: {} }>();
並讓打字稿推斷其他兩個泛型
您可以完全省略 Feature defenition,因為它取決於Geometry
和Properties
function test<
Geometry extends GeoJSON.Geometry,
Properties extends {},
>() {
const addFeature = (feature: { shape: Geometry; properties: Properties }) => {
switch (feature.shape.type) {
case "Point":
break;
}
};
return {
addFeature,
};
}
test<GeoJSON.Polygon, {}>();
或在別處定義
type Feature<G extends GeoJSON.Geometry, P extends {}> = {
shape: G;
properties: P;
}
function test<
Geometry extends GeoJSON.Geometry,
Properties extends {},
>() {
const addFeature = (feature: Feature<Geometry, Properties>) => {
switch (feature.shape.type) {
case "Point":
break;
}
};
return {
addFeature,
};
}
test<GeoJSON.Polygon, {}>();
但它仍然會有一些問題,如果你有很多 Feature 道具
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.