programing

TypeScript에서 함수 인터페이스를 구현할 수 있습니까?

cafebook 2023. 7. 7. 21:08
반응형

TypeScript에서 함수 인터페이스를 구현할 수 있습니까?

저는 이것을 할 수 있기를 바랍니다.

class MyFunc extends ((s: string) => boolean) { ... }

의 예로서MyFunc문자열을 입력으로 사용하고 다음과 같이 부울을 반환하는 함수로 사용할 수 있습니다.

const f = new MyFunc();
const b: boolean = f('someString');

이것이 TypeScript에서 가능합니까?

스칼라와 같은 언어에서는 유형을 확장할 수 있습니다.String => Boolean그리고 제공합니다.apply이를 위한 방법.

class MyFunc extends (String => Boolean)
val f = new MyFunc()
val b: Boolean = f("someString")

아마도 당신은 이와 같은 것을 생각하고 있을 것입니다.

interface FunctionInterface {
    (s: string): boolean;
}

const f: FunctionInterface = s => true;
const b: boolean = f('someString');

기본값은 없습니다.applyTypeScript의 개념이지만 함수이기도 한 입력된 개체를 만드는 방법이 있습니다.

interface MyCallable {
    (param1: string, param2: number): string;

    prop1: string;
    prop2: number;
    extraMethod: (param1: boolean) => boolean;
}

function makeMyCallable(prop1: string, prop2: number): MyCallable {
    let that = ((param1: string, param2: number) => param1 + param2) as MyCallable;

    that.prop1 = prop1;
    that.prop2 = prop2;
    that.extraMethod = (param1: boolean) => !param1;

    return that;
}

let mc = makeMyCallable("3", 4);

mc("3", 4);
mc.prop1 = "string";
mc.prop2 = 5;
mc.extraMethod(false);

문자열을 수락하고 부울을 반환하는 단순 함수만 원하는 경우 클래스를 사용할 필요가 없습니다.

const myFunc = (s: string): boolean => {
  return s !== "";  //whatever logic is needed here
};

그러나 예, TypeScript에서 클래스를 확장할 수 있습니다.

class MyBaseClass {
  constructor() { }

  public doThing = (s: string): boolean => {
    return s !== "";  //whatever logic is needed here
  }
}

class MyFunc extends MyBaseClass {
  constructor() {
    super();
  }
}

const f = new MyFunc();
const b = f.doThing("hi"); //returns a boolean

주석에 대한 응답을 위해 업데이트됨

아래의 다른 답변에서 언급한 바와 같이, 당신은 정말로 할 수 없습니다.new클래스를 위로 이동하고 해당 인스턴스를 변수에 할당한 다음 함수로 호출합니다.그러나 다음과 같이 생성 시에도 이 작업을 수행할 수 있습니다.

class MyBaseClass {
  constructor() { }

  public doThing = (s: string): boolean => {
    return s !== "";  //whatever logic is needed here
  }
}

class MyFunc extends MyBaseClass {
  constructor(private s: string) {
    super();
    this.doThing(this.s);
  }
}

const f = new MyFunc("hi"); //returns a boolean

여기 Typescript 놀이터에서 위의 코드로 플레이할 수 있습니다.

인터페이스에 이 기능만 있는 경우 다음과 같이 정의할 수 있습니다.

type FuncType = (s: string) => boolean;

처럼 사용하기 위해서는

const myFunc: FuncType;
function getFunction(): FuncType {}

사용 사례에 따라 다릅니다.여기 몇 가지 방법이 있습니다.https://typescriptlang.org/play/ ...

어떻게든 우리는 수입했습니다.

  • 인터페이스 @ https://stackoverflow.com/a/42841742/9412937 로.
  • 함수 유형으로
type fInterface = (...params: fArgs) => fRet
  • 별개의 활자로서
type fArgs = [number, string]
type fRet = boolean

상관 없음 - 와 호환 가능합니다.

그리고 우리는 기능이 잘못 구현되었습니다.

function nop() {}
  1. 수동으로 매개 변수 유형 선택
function isEqual0(x: fArgs[0], y: fArgs[1]): fRet {
  //return x == y //TS-ERROR: This condition will always return 'false' since the types 'number' and 'string' have no overlap.ts(2367)
  return `${x}` == y
}
  1. 파괴 포함
function isEqual1(...args: fArgs): fRet {
  const [x, y] = args
  return `${x}` == y
}
  1. 과부하로.엄격하게 사용하지만 구현 중에 모든 매개 변수는any.
function isEqual2(...args: Parameters<fInterface>): ReturnType<fInterface>
function isEqual2(x: any, y: any) {
  return x == y
}
  1. 결국 우리는 (기능 입력과 같은) 재입력을 통해 검증할 수 있습니다.또한 어떤 경우에도 부모 모듈에 유형 검증이 있을 것입니다.
function isEqual3(x: any, y: any) {
  const valid: typeof  isEqual3 extends fInterface ? true : never = true
  if (!valid)
    throw Error()
  return x == y
}

const _exports = {
  isEqual0, isEqual1, isEqual2, isEqual3, nop
}
, _exportCheck = _exports as  Record<keyof typeof _exports, fInterface> //TS-ERROR The types returned by 'nop(...)' are incompatible between these types.

module.exports = _exportCheck
export default _exportCheck
export {
  isEqual0, isEqual1, isEqual2, nop
}

무언가 잘못되었다면 TS-Error를 달성할 수 있는 많은 방법들.

언급URL : https://stackoverflow.com/questions/42840466/is-it-possible-to-implement-a-function-interface-in-typescript

반응형