我可以有一个包含其他类型的子部分的泛型类型吗?
Can I have a generic type which contains a subsection of other types?
我有几个接口,它们总是有一个共同的 field
成员,它本身总是有一个 body
字段,但也可以有其他字段。
我想用 T
实现一个通用抽象 class,它表示所有接口的这个子部分,以便抽象 class 可以实现可以访问 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;
}
}
Typescript 可以吗?
我会选择:
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
只要它扩展 AbstractStructure
就可以使用界面,它定义了您想要的字段。
我有几个接口,它们总是有一个共同的 field
成员,它本身总是有一个 body
字段,但也可以有其他字段。
我想用 T
实现一个通用抽象 class,它表示所有接口的这个子部分,以便抽象 class 可以实现可以访问 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;
}
}
Typescript 可以吗?
我会选择:
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
只要它扩展 AbstractStructure
就可以使用界面,它定义了您想要的字段。