sorry for my poor english; I'll show you the code;
class Service {
word: string = "hi"
get actions(): { hello: Function, greet: Function } {
return this
}
}
class TestService extends Service {
hello() {}
greet() {}
}
enter code here
const service = new TestService()
service.hello() // good
console.log(service.word) // error
how can i define a type that can makes actions only return all the Function properties? this might be a little confused, please notice that actions define in parent class, but i want its type are Part of inherit class's property
sorry for my poor description, i just update my code
Anything that should not be visible outside the class can be hidden using private
/protected
:
abstract class Service
{
private word: string = "hi"
// These would be required, otherwise `return this` is an error in `actions`.
abstract hello(): void;
abstract greet(): void;
get actions(): { hello: Function, greet: Function }
{
return this
}
}
class TestService extends Service
{
hello() { }
greet() { }
}
const service = new TestService()
service.hello() // good
console.log(service.word) // error
As long as you are using classes directly you always get the full interface of the class. If you want to restrict the type more dynamically you probably need to work with functions returning interfaces/advanced types.
e.g.
type FunctionKeys<T> = {
[K in keyof T]: T[K] extends Function ? K : never
}[keyof T]
function createService()
{
class Service
{
word: string = "hi"
hello() { }
greet() { }
get actions(): { hello: Function, greet: Function }
{
return this
}
}
// Restricts the type to only the functions of Service
const service: Pick<Service, FunctionKeys<Service>> = new Service();
return service;
}
const service = createService()
service.hello() // good
console.log(service.word) // error
In this example, if a function is added to the Service
class, it will automatically become available on the constructed instance.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments