Typescript Error:type 'number' Is Not Assignable To Type 'never'
Solution 1:
You are getting that error because TypeScript can't infer that this.opts[key] and opts[key] are the same type. If you were to cover up each half of the =:
opts[key]could be aFunction,null,boolean, ornumberthis.opts[key]needs to receive aFunction,null,boolean, ornumberdepending on the value ofkey, which we don't know- the only supertype in common for
Function,null,boolean, andnumberisnever, so that's the type that TypeScript wants forthis.opts[key]
Interestingly, if you were to extract this to an anonymous generic function, it works: Within a single assignment Typescript can infer and use the type Opts[K]. jcalz suggests a similar solution in this similar question.
if (typeof opts[key] !== "undefined") {
// this.opts[key] = opts[key];
(<K extends keyof Opts>(k: K) => { this.opts[k] = opts[k]; })(key);
}
That said, I would use the spread operator as in Mukesh Soni's answer, ending your assignment of this.opts with ...opts, or use Object.assign. There's a slight risk that the passed opts contains extra keys, but Typescript should ensure otherwise at compile time. (For that matter, if you're expecting opts to be optional and potentially incomplete, it should probably be defined as opts?: Partial<Opts>.)
classNES {
constructor(opts?: Partial<Opts>) {
this.opts = Object.assign({
onFrame() { },
onAudioSample: null,
emulateSound: true,
sampleRate: 44100,
}, opts);
}
opts: Opts
}
See also:Object spread vs. Object.assign, which notes that the solutions are quite similar and both applicable for default options values.
Solution 2:
I don't know why you are getting that error. One other way to merge both the options might be to use spread operators.
this.opts = {
onFrame() { },
onAudioSample: null,
emulateSound: true,
sampleRate: 44100,
...opts
};
Solution 3:
If you put the as any after the property access, TypeScript will check that key is a valid key
if (typeof opts[key] !== "undefined") {
(this.opts[key] asany) = opts[key];
}
Post a Comment for "Typescript Error:type 'number' Is Not Assignable To Type 'never'"