Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

javascript - How to infer parameter type in TypeScript?

How infer parameter type?

I want to implement a state management library similar to redux, and I have trouble defining types. The prototype is as follows:


interface IModel<S, A> {
  state: S
  action: IActions<S, A>
}

type IActions<S, A> =  {
  [K in keyof A]: (state: S, payload: ???) => void // `???` How should it be defined here
}

class Model<T,A> implements IModel<T,A>{
  //...
}

// examples

const model=new Model({
  state:{name:"foo"},
  action:{
    setName:(state,name: string)=>{
      //...
    },
    fetchAccount:(state,payload: {
      id: number,
      locked: boolean,
      ...
})=>{
      //...
    }
  }
})

//
let state={name:''}
model.action.setName(state,'bar') // ok
model.action.setName(state,123)   // error
question from:https://stackoverflow.com/questions/65871538/how-to-infer-parameter-type-in-typescript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to have strict type checking in the specific case where your method names match your state property names, you can use template literal types and mapped type as clauses. This requires Typescript 4.1 or newer.

The general gist is to take the state keys (in this case name), and map them to corresponding method names (setName) with the correct signatures ((state: State, value: string) => void).

type Actions<State> = {
  [K in keyof State & string as `set${Capitalize<K>}`]: (state: State, value: State[K]) => void;
}

type Model<State> = {
  state: State;
  actions: Actions<State>;
}

const model: Model<{ name: string }> = {
  state: {
    name: 'foo',
  },
  actions: {
    setName(state, value) {
      state.name = value;
    }
  }
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...