I'm bulk importing a bunch of properties with
import * as actionCreators from './billingUtil2';
and TypeScript is correctly identifying each export inside of actionCreators
. Is it possible to "spread" those members into an interface? Ideally something like this, but valid
interface componentState {
...actionCreators
}
My use case is, I'd like to create a React component and accurately describe the shape of the props it'll be receiving from Redux. So ideally something along these lines
import * as actionCreators from './billingUtil2';
interface State {
name: string;
age: number
}
interface componentState extends State {
...actionCreators
}
and then I could tell TypeScript to expect props of the form componentState
.
My redux reducers would already be returning results implementing an interface; my main goal here is to avoid manually typing out each action creator.
If we are using TypeScript version 4 or beyond, we can spread tuple generic parameter types. This is useful to help TypeScript better infer types on expressions that involve tuples.
TypeScript Basics. The spread operator is a new addition to the features available in the JavaScript ES6 version. The spread operator is used to expand or spread an iterable or an array.
Extending Interfaces in TypeScript # Use the extends keyword to extend interfaces in TypeScript, e.g. interface Dog extends Animal {age: number;} . The extends keyword allows us to copy the members from other named types and add new members to the final, more generic interface. Copied!
To extend types in TypeScript, we can use the extends keyword. to create the UserEvent interface that extends the Event type. We extend it by adding the string UserId field in UserEvent and inheriting the rest from Event .
You could create an Intersection Type
import * as actionCreators from './billingUtil2';
type MyState = typeof actionCreators & {
name: string
age: number
}
or from your code in the second section above, where you had the State
interface, you could do
import * as actionCreators from './billingUtil2';
interface State {
name: string;
age: number
}
type componentShape = typeof actionCreators & State;
or you could similarly do
type acT = typeof actionCreators
interface MyState extends acT {
name; age;
}
class Comp extends React.Component<{}, MyState> {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With