我如何在 class 中定义一个方法,它 return 只是 class 的一部分

How can i define a method in a class that it return only part of the class

抱歉我的英语不好;我给你看代码;

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

我如何定义一个类型,它可以只return所有函数属性进行操作?这可能有点混乱,请注意在父 class 中定义的操作,但我希望它的类型是继承 class 的 属性

的一部分

抱歉我描述不当,我刚刚更新了我的代码

我想你想使用 class 继承。查找更多 here

制作 class Service 的子class,并制作 Service class 扩展子class.

    class Service extends SubclassService {
      word: string = "hi"
    }
    class Subclass {
      hello() {}
      greet() {}
      get actions(): { hello: Function, greet: Function } {
        return this
      }
    }

    const service = new SubclassService()
    service.hello() // good
    console.log(service.word) // error

可以使用 private/protected 隐藏在 class 之外不可见的任何内容:

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

只要您直接使用 classes,您总是可以获得 class 的完整界面。如果您想更动态地限制类型,您可能需要使用返回 interfaces/advanced 类型的函数。

例如

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

在此示例中,如果将函数添加到 Service class,它将自动在构造的实例上可用。