简体   繁体   中英

Custom interface TypeScript

I would type to get custom TypeScript interface :

export type CreateActions<T> = T;

So I can do something like :

const actionCreators = {
  add: null,
  remove: null
}

const { creators }: { creators: CreateActions<ActionCreators> } = createActions('Jedi', actionCreators);

creators.add({ name: 'Yoda' });

So I want to get method "add" to be understood by TypeScript.

Thanks for your advice !

Here's the Playground

EDIT :

It's difficult to explain, I'm sorry.

What I want is : I have an object that have some keys. It's values are "null" or "object".

I want a method that takes those keys and generate methods for those.

So if I have

const myObject = {
  myKey: null,
  otherKey: null,
}

I want my method to output :

{
  myKey: () => ...,
  otherKey: () => ...
}

So, I want to add TypeScript validations based on my first object. This object (myObject in my case) is not known, and its keys may vary.

If you want to have functions in your interface properties, declare their type which is Function . Also if you don't know at compile time what keys they'll be placed at, then be aware that TypeScript will also only be able to help with as much info as you give him.

I see that in your example, you define these functions after the object is created, so you'll need to declare them as nullable, that means adding a | null | null meaning they can be null (as they are in their initial state).

Which makes the final code of your interface like this :

interface ActionCreators {
    [key: string]: Function | null
}

Here is the playground link of your case, with an example an error at the end when trying to assign something other than a function : Playground link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM