How can I create an instantiation of a template type using compiler API in a decorator? #3328
-
Problem statementI want to create a decorator @extension("x-foo", Json<"value here">) which should simplify this to: @foo("value here") I didn't find any way to instantiate a template import { createRekeyableMap } from "@typespec/compiler/utils";
import { $extension } from "@typespec/json-schema";
/**
* @param {import("@typespec/compiler").DecoratorContext} context
* @param {import("@typespec/compiler").Type} target
* @param {import("@typespec/compiler").StringLiteral} value
*/
export function $foo(context, target, value) {
$extension(context, target, "x-foo", {
kind: "Model",
name: "Json",
namespace: { name: "JsonSchema" },
properties: createRekeyableMap([["value", { type: value }]])
})
} Basically there is quite a lack of documentation in the export type CreateTypeProps = Omit<Type, "isFinished" | keyof TypePrototype>;
export interface Checker {
createType<T extends Type extends any ? CreateTypeProps : never>(typeDef: T): T & TypePrototype & {
isFinished: boolean;
};
} Another thing I tried is this: context.program.resolveTypeReference("TypeSpec.JsonSchema.Json"); but it returns: [
undefined,
[
{
code: 'invalid-template-args',
severity: 'error',
message: "Template argument 'Data' is required and not specified.",
target: [Object]
}
]
] Then I tried context.program.resolveTypeReference("TypeSpec.JsonSchema.Json<\"foo\">"); but it returns [ undefined, [] ] |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Yeah But seeing this is to simplify the
|
Beta Was this translation helpful? Give feedback.
-
I would love some syntax better than
Anyway, it's just my 5 cents, and it seems like you already have a better idea for the direction of
Only if this matters to you or someone else. I don't mind any breaking changes at the stage I'm using TypeSpec yet, and would even prefer improvement over a breaking change from my side.
That would be perfect, indeed! In my use case, I'm writing a library that simplifies adding several Created an issue for this #3336 |
Beta Was this translation helpful? Give feedback.
Yeah
resolveTypeReference
is explicitly designed to not instantiate further templates(readonly). I don't think we have a good API for this.But seeing this is to simplify the
@JsonSchema.extension
decorator i think there is a few things:Json<T>
wrapper for values in this decorator. However that is a breaking change(to change that specific decorator) and we haven't decided yet if we'll take it.