typescript - Recursive type definitions does not seem to work handle generics? -


i think bug in typescript , filed issue here. don't expect fixed (at least not soon, want ask guys, happen have idea better solution/work-around create_1?

code

type recursivepartial<t> = {     [p in keyof t]?: recursivepartial<t[p]>; };  type state<t> = { value: t };  function create_1<t>(){      let _x: recursivepartial<state<t>>;     let _y: state<recursivepartial<t>>;      _x = _y; }  function create_2<t>(){  /*   */      let x: recursivepartial<state<t>>;     let y: state<t>;      /*         type 'state<t>' not assignable type recursivepartial<state<t>>'.             types of property 'value' incompatible.                 type 't' not assignable type recursivepartial<t>[p]>'.                     type 't[string]' not assignable type 'recursivepartial<t[p]>'.     */      x = y;  } 

expected behavior: had expected second example valid typescript, i.e. state should assignable recursivepartial>. should case state partial of self given t same type.

actual behavior: type error (see above), seems recursive type definition breaks when encounters generic?

ts playground link code , type error can confirmed here; ts-playground example

it looks bug me. workarounds:

as noticed in the github issue, first , best workaround turn on strictnullchecks compiler option. recommend turning on , keeping on in general, since useful.


if don't want that, can use type assertion tell compiler know type better does. if compiler resistant doing assertion, can pass through assertion of any, so:

function create_2<t>(){     let x: recursivepartial<state<t>>;     let y: state<t>;     x = y recursivepartial<state<t>>; // know it! } 

if don't want that, change definition of recursivepartial<> following:

type recursivepartial<t> = {     [p in keyof t]?: t[p] | recursivepartial<t[p]>; }; 

this is, believe, same thing, compiler has easier time seeing can assign value of type t variable of type recursivepartial<t>.


hope helps. luck!


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -