Repository navigation
How to Retrieve the Name of a Type Programmatically? #263
Replies: 2 comments
|
can you further share your code snippets. |
|
Not directly from a TypeScript interface or generic type parameter at runtime: those types are erased when TypeScript becomes JavaScript. Reflection metadata does not recover an arbitrary interface name, and TypeChat does not provide a The generic argument and the schema-name string serve different purposes: One practical way to reduce refactoring churn is to give the schema a stable exported root alias. For example, in the schema: export interface Sentiment {
sentiment: "positive" | "negative" | "neutral";
}
export type Response = Sentiment;With that file's source supplied as import type { Response } from "./schema.js";
import { createTypeScriptJsonValidator } from "typechat/ts";
const validator = createTypeScriptJsonValidator<Response>(schemaText, "Response");You can then rename the implementation type and update the alias without changing the validator's root name. Renaming Build-time code generation can automate names if an application needs that, but it is additional tooling, not something the generic type parameter supplies at runtime. This response was created with the assistance of AI. |
Uh oh!
There was an error while loading. Please reload this page.
The
createTypeScriptJsonValidatorfunction requires the name of a JSON target type from the schema. If I rename a type in the schema, I must update the corresponding JSON target type string. Failing to do so will result in the following error:Is there a way to programmatically obtain the name of a type without manually typing the string? Perhaps using reflection metadata or something similar?
All reactions