arktype
arktype copied to clipboard
Defining ArkType type() based on a TypeScript type it satisfies
Request a feature
🤷 Motivation
A lot of times there already exists a TS type as a source of truth, which some runtime data needs to be asserted as using validation. Currently, I have to define the ArkType type() without type-safety connecting it with the original TS type.
Using type({} satisfies Record<keyof TsType, unknown>) breaks IntelliSense on the ArkType string validator definition.
💡 Solution
import { type } from 'arktype'
type MyType = {
name: string
}
const MyArkType = type.satisfies<MyType>().define({
// all keys from MyType must be defined and match MyType
name: 'string',
// @ts-expect-error Not defined in MyType
not_defined: 'string',
// @ts-expect-error name should be a string
name: 'number'
})
Workaround
const _unusedVarOnlyForTypeCheck = {} as typeof MyArkType.infer satisfies MyType
type MyType = {
name: string
}
const MyArkType = declare<MyType>().type({
name: "string",
})
thanks @travislwatson, that's right!
see the declare docs here:
https://arktype.io/docs/declare