GithubHelp home page GithubHelp logo

Comments (3)

sinclairzx81 avatar sinclairzx81 commented on June 23, 2024

@ehaynes99 Hi! This is an interesting one.

When creating a function with a generic parameter of type TSchema, that parameter cannot be used to enforce types with Static, StaticEncode, or StaticDecode. It appears that the effective type in this scenario is just any. All of the below compile under strict mode:

So passing a TSchema to a Static inference type will infer as unknown.

type T = Static<TSchema>        // type T = unknown
type D = StaticDecode<TSchema>  // type D = unknown
type E = StaticEncode<TSchema>  // type E = unknown

This extends to functions when Static is used as a return type.

// all these are fine from the compilers standpoint
const getStatic = <T extends TSchema>(schema: T): /* Static<T> */ unknown => 'anything'
const getStaticEncode = <T extends TSchema>(schema: T): /* StaticEncode<T> */ unknown  => true
const getStaticDecode = <T extends TSchema>(schema: T): /* StaticDecode<T> */ unknown => undefined

However, if you make the return type part of the generic signature (introduced as R), you can get TypeScript to raise an error.

TypeScript Link Here

// error type: 'R' could be instantiated with an arbitrary type which could be unrelated to '...'

const getStatic = <T extends TSchema, R = Static<T>>(schema: T): R => {
  return 'anything' // Type 'string' is not assignable to type 'R'
}

const getStaticEncode = <T extends TSchema, R = StaticEncode<T>>(schema: T): R => {
  return true // Type 'boolean' is not assignable to type 'R'
}

const getStaticDecode = <T extends TSchema, R = StaticDecode<T>>(schema: T): R => {
  return undefined // // Type 'undefined' is not assignable to type 'R'
}

I believe the above works as it makes TypeScript aware that the return type R is directly dependent upon the parameter type T and where both T and R cannot be known in advance. TypeBox uses this technique internally as it helps to ensure type safety and also because it can lead to more efficient inference (as TypeScript tends to evaluate return types differently in support of control flow analysis ... this technique by-passes it)

Hope this helps!
S

from typebox.

ehaynes99 avatar ehaynes99 commented on June 23, 2024

Huh, yeah, that's interesting. That does indeed solve the problem, but this is one of those covariance/contravariance issues that really feel broken. TS allows narrowing in subtypes, but then doesn't consider the possibility of that narrowing when enforcing types. I really didn't expect it here, though... Any subtype of TSchema will have a static property that is assignable to unknown, but unknown is not necessarily assignable to the type of the static property of arbitrary subtypes of TSchema.

It's similar to:

export interface Example1 {
  example(value: string | number): string
}

const example1: Example1 = {
  example: (value: string) => value.toUpperCase(),
}

// runtime error!
example1.example(111)

export interface Example2 {
  example(value: string): string
}

// fine
const example2: Example2 = {
  example: (value: string | number) => String(value),
}

// surprising lack of consistency
export interface Example3 {
  example: (value: string | number) => string
}

const example3: Example3 = {
  // compile error:
  // typescript: Type '(value: string) => string' is not
  // assignable to type '(value: string | number) => string'.
  example: (value: string) => value.toUpperCase(),
}

from typebox.

ehaynes99 avatar ehaynes99 commented on June 23, 2024

Actually, on further inspection, that doesn't work either. Supplying the second generic parameter solves the problem above and prevents returning an arbitrary, unrelated value, but it also creates the opposite problem in that a verified Static<T> isn't necessarily the same type as R. For example:

export const check = <T extends TSchema, R = StaticEncode<T>>(
  schema: T, //
  value: unknown,
): R => {
  if (!Value.Check(schema, value)) {
    throw new TypeError('Invalid value')
  }

  // typescript: Type 'Static<T>' is not assignable to type 'R'.
  //   'Static<T>' is assignable to the constraint of type 'R', but 'R'
  //   could be instantiated with a different subtype of constraint 'unknown'. [2322]
  return value
}

That error is correct (and honestly what I expected in the original scenario). Since the return type is now specified by the caller, R could be any arbitrary type:

const value: number = check<TString, number>(Type.String(), 'hello')

Even with an added constraint of R extends StaticEncode<T> = StaticEncode<T> it's still not safe. E.g.

const Model = Type.Object({
  name: Type.String(),
  age: Type.Optional(Type.Number()),
})
type Model = Static<typeof Model>
type Model2 = Model & {
  email: string
}

// value is only guaranteed to be a `Model`, not a `Model2`, but the generic parameter
const value: Model2 = check<typeof Model, Model2>(Model, {
  name: 'Joe Schmoe',
  age: 42,
})

An in fact, the compiler will infer the type from the assignment even if you omit the generic parameters:
image

I'm not sure there's really any solution here. It's too fundamental to how the derived types work. The problem will exist in one direction or the other. I think I'm better off with the original case. At least there, I can test my generic functions' output, and the callers will have properly enforced types.

from typebox.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.