単にその型の持つプロパティを足し算したようなものです。JavaScriptが分かる人ならオブジェクト同士をObject.assign
したようなものだと想像すると分かりやすいと思います。
Intersection の例
interface Foo {
foo: string;
}
interface Bar {
bar: string;
}
type FooBar = Foo & Bar;
// 以下と同等
// interface FooBar {
// foo: string;
// bar: string;
// }
const fooBar: FooBar = {
foo: 'foo',
bar: 'bar'
};
使用場所
個人的には、自分で渡したいのはT
だけだけど、実際の関数渡されるのはT & U
にしたいというのような場合に使っています。ここで言うU
という型は、デフォルト値だったり別な所から渡ってきたりするものです。
interface Props {
something: any;
}
interface RouterProps {
history: any;
}
const Router = {
// モック
get(): RouterProps {
return;
}
}
// こっちは自分から呼び出すことはしない
const realRender: (props: Props & RouterProps) => null = props => null;
const render: (props: Props) => null = props => {
const routerProps = Router.get();
const realProps = {
...props,
...routerProps,
};
return realRender(realProps);
};
例えばこれはDecoratorで同じプロパティを使う時とか、ReactのContextとprops
で一緒に渡したい時とかに使うことができます。