Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript interface with spread members

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.

like image 389
Adam Rackis Avatar asked Apr 25 '17 22:04

Adam Rackis


People also ask

Can you spread types in TypeScript?

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.

What is spread operator in TypeScript?

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.

How do you use extended interface TypeScript?

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!

Can you extend types in TypeScript?

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 .


1 Answers

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> {

}
like image 95
wkrueger Avatar answered Oct 31 '22 05:10

wkrueger