superstruct icon indicating copy to clipboard operation
superstruct copied to clipboard

use create with a runtime computed struct with typescript

Open Louis-Tian opened this issue 3 years ago • 2 comments

Hi guys, I am looking for some guardian on how to use create method with a struct that is computed at runtime. The problem is with type inference in TypeScript. Here is a minimum example:

const S = string();
const N = number();
const useString = (bool: Boolean) => (bool ? S : N);
create("", useString(true));

https://codesandbox.io/embed/laughing-water-redbr4?fontsize=14&hidenavigation=1&theme=dark

TS compiler gives the following error

Argument of type 'Struct<string, null> | Struct<number, null>' is not assignable to parameter of type 'Struct<string, null>'.
  Type 'Struct<number, null>' is not assignable to type 'Struct<string, null>'.
    Types of property 'TYPE' are incompatible.
      Type 'number' is not assignable to type 'string'.ts(2345)

Tried a dozen of other ways. So far no luck. Any pointer is appreciated. Thanks

Louis-Tian avatar Mar 07 '22 04:03 Louis-Tian

using the dynamic

const S = defaulted(string(), "");
const N = defaulted(number(), 0);
const T = dynamic((value) => value ? S : N);
create(1, T);

gives

  Type 'Struct<number, null>' is not assignable to type 'Struct<string, any>'.
    Types of property 'TYPE' are incompatible.
      Type 'number' is not assignable to type 'string'.

Louis-Tian avatar Mar 07 '22 04:03 Louis-Tian

@Louis-Tian I don't see the type checking errors coming up in the sandbox, do you know how I can get them to show up?

ianstormtaylor avatar Jun 02 '22 13:06 ianstormtaylor