Repository navigation
|
Hi, In some cases the inference with morphs does not work. A parser is always meant to parse unknown types into something. But here the typing of the morph (which extends the succeeded validation?) is used as the input type instead of the regular unknown. import { type } from "arktype"
import type { Type, Out } from "arktype";
type NullableStr = string | null;
// TS2322: Type Type<(In: string | null) => Out<NullableStr>, {}> is not assignable to type Type<(input: unknown) => Out<NullableStr>, {}>
// Types of property t are incompatible.
// Type (In: string | null) => Out<NullableStr> is not assignable to type (input: unknown) => Out<NullableStr>
// Types of parameters In and input are incompatible.
// Type unknown is not assignable to type string | null
const parseStr: Type<(input: unknown) => Out<NullableStr>> = type("string.trim | null").pipe((value: NullableStr): NullableStr => value === '' ? null : value); |
Replies: 1 comment 1 reply
|
The input inside import { type, type Type, type Out } from "arktype"
type NullableStr = string | null
const parseStr: Type<(input: NullableStr) => Out<NullableStr>> =
type("string.trim | null").pipe(
(value): NullableStr => value === "" ? null : value
)
const input: unknown = " hello "
const result = parseStr(input) // NullableStr | ArkErrorsIf the exported contract only needs to be a throwing parser, rather than exposing the schema's composition API, wrap export function parseNullableString(input: unknown): NullableStr {
return parseStr.assert(input)
}Tested with ArkType 2.2.8 and TypeScript 5.9.3: whitespace is trimmed, an empty/whitespace-only string becomes |
In the past months there was a new API released:
type.declare<MyType, { side: "out" }>()which solved the issue for me. I was able to say that the arktype is a validator that produces the type at the output level.