I'm trying to declare a type which it should only accept objects where they extend another type.
For example:
export interface A extends B {
aProp: string;
}
export interface B {
bProp: string;
// Feels wrong but how to tell something like ReadonlyArray<subClass extends B>?
// I need children to contain A (or anything that extends B) & B properties
children: ReadonlyArray<any & B>;
childrenThatDoesntWork: ReadonlyArray<any extends B>; // <-- error here
}
class SomeClass {
fun(obj: any extends B) { // <-- error '?' expected
}
}
How to do this?
Thanks!
Here is my solution:
export interface A extends B {
aProp: string;
}
export interface B {
bProp: string;
// Feels wrong but how to tell something like ReadonlyArray<subClass extends B>?
// I need children to contain A (or anything that extends B) & B properties
children: ReadonlyArray<A | B>;
childrenThatDoesntWork: ReadonlyArray<B>;
}
class SomeClass {
fun<T extends B>(obj: T) {
}
}
Please check if it works for your case. If not, please provide the code for tests
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.