arktype icon indicating copy to clipboard operation
arktype copied to clipboard

Defining ArkType type() based on a TypeScript type it satisfies

Open DrJume opened this issue 1 year ago • 2 comments

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

DrJume avatar May 15 '25 16:05 DrJume

type MyType = {
  name: string
}

const MyArkType = declare<MyType>().type({
  name: "string",
})

travislwatson avatar May 17 '25 20:05 travislwatson

thanks @travislwatson, that's right!

see the declare docs here:

https://arktype.io/docs/declare

ssalbdivad avatar Dec 15 '25 21:12 ssalbdivad