Typescriptで以下のようなinterfaceを書き、func
に代入します。
interface hoge{
(str:string):void;
text?:string;
}
let func:hoge = (str:string) => {console.log(str)};
このように変数func
に代入するとエラーなくコンパイルされますが、
オプションであるtext
をfunc
に代入する時点で指定することはできますか?
スタック・オーバーフローはプログラマーとプログラミングに熱心な人のためのQ&Aサイトです。すぐ登録できます。
登録してこのコミュニティに参加する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' }
);