我有幾個介面,它們總是有一個field共同的成員,它本身總是有一個body欄位,但也可以有其他欄位。
我想實作一個通用抽象類,T它代表所有介面的這個子部分,以便抽象類可以實作可以訪問fields.body這種型別的函式。
這是一個例子:
interface SomeInterface{
title:string;
fields: {
title: { "en-US": string };
body: { "en-US": any };
some:{inter:string};
different:string;
}
}
interface SimilarbutNotSameInterface{
description:string;
fields: {
title: { "en-US": string };
body: { "en-US": any };
similar:number;
not:string;
}
}
abstract class Manipulator<T>{
abstract allInterfaces:T;
Manipulator(): T {
SomeOtherfunction(this.allInterfaces.fields.body["en-US"]);
return this.allInterfaces;
}
}
打字稿可以做到這一點嗎?
uj5u.com熱心網友回復:
我會去:
interface AbstractStructure {
fields: Array<{
body: unknown;
}>
}
interface Structure1 extends AbstractStructure {
fields: Array<{
body: unknown;
property1: string;
}>
}
interface Structure2 extends AbstractStructure {
fields: Array<{
body: unknown;
property2: string;
}>
}
abstract class AbstractManipulator<T extends AbstractStructure> {
abstract structures: T[];
manipulate(): T[] {
// We can safely access this property since it is present on AbstractStructure type
console.log(this.structures[0].fields[0].body);
return this.structures;
}
}
這種方式AbstractManipulator將與 interface 一起使用,只要它 extends AbstractStructure,它定義了您想要的欄位。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/416611.html
標籤:
上一篇:將值傳遞給具有泛型型別的結構
