deepkit / deepkit-framework

A new full-featured and high-performance TypeScript framework
https://deepkit.io/
MIT License
3.24k stars 123 forks source link

[type]: conditional type inference unexpected #524

Open kelvinschen opened 11 months ago

kelvinschen commented 11 months ago
import { typeOf, valuesOf, ReflectionClass, validate, is } from "@deepkit/type";

type Foo<T> = T extends [...infer P extends string[], infer L] ? L : never

type Bar = Foo<[string, string, number]> // Bar is number

console.log('valRes', is<Bar>('hello'))  // true (expect to be false)
console.log('valRes', is<Bar>(1)) // false (expect to be true)
console.log('valRes', is<number>(1)) // true
console.log('type', typeOf<Bar>()) // kind: 5 (expect to be 6)
  "dependencies": {
    "@deepkit/core": "^1.0.1-alpha.108",
    "@deepkit/type": "^1.0.1-alpha.108"
  },
  "devDependencies": {
    "@deepkit/type-compiler": "^1.0.1-alpha.108",
    "@types/node": "20.8.6",
    "ts-node": "10.9.1",
    "typescript": "^5.1"
  }

codesandbox

it seems the inference of Bar result in 'string' rather than 'number'

marcj commented 11 months ago

Infer operations with constraints are not implemented yet.

https://github.com/deepkit/deepkit-framework/blob/acb2d72f242a742fe99fdcf9fba892faea701e08/packages/type-compiler/src/compiler.ts#L1589

We need a new bytecode OP inferConstrained or something like that to have it backward compatible, and then consume TypeParameterDeclaration.constraint in the AST node (narrowed.typeParameter.constraint)