1

Typescriptで以下のようなinterfaceを書き、funcに代入します。

 interface hoge{
  (str:string):void;
  text?:string;
 }

let func:hoge = (str:string) => {console.log(str)};

このように変数funcに代入するとエラーなくコンパイルされますが、
オプションであるtextfuncに代入する時点で指定することはできますか?

1 件の回答 1

0

stackoverflow.comでの類似質問
https://stackoverflow.com/q/12766528/4366193

例えばinterfaceのインスタンスを生成するBuilderを定義する方法があります。

hoge という変数を使いたかったので、interfaceは Hoge に変えさせていただきました。

 interface Hoge {
  (str:string):void;
  text?:string;
 }

const hogeBuilder = (f: (str: string) => void, text?: string): Hoge => {
  const hoge: Hoge = f;
  hoge.text = text;

  return hoge;
};

const func1: Hoge = hogeBuilder((str:string) => { console.log(str); });

const func2: Hoge = hogeBuilder((str:string) => { console.log(str); }, 'text exists');

func1('Hello');
console.log(`func1.text: ${func1.text}`);

func2('Hello, world');
console.log(`func2.text: ${func2.text}`);

または、即時実行関数を使って生成したものを返す方法も考えられます。

 interface Hoge {
  (str:string):void;
  text?:string;
 }

const func: Hoge = (() => {
  const hoge: Hoge = (str:string) => { console.log(str); };
  hoge.text = 'text exists';

  return hoge;
})();

他には Object.assign() を使用する方法もあるようです。

 interface Hoge {
  (str:string):void;
  text?:string;
 }

const func: Hoge = Object.assign(
   (str: string) => { console.log(str); },
   { text: 'fuga' }
);

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。