Skip to main content
Version: Latest (0.56.x)

Built-in Decorators

TypeSpec

@deprecated

Mark this type as deprecated.

NOTE: This decorator should not be used, use the #deprecated directive instead.

@deprecated(message: valueof string)

Target

unknown

Parameters

NameTypeDescription
messagevalueof stringDeprecation message.

Examples

Use the #deprecated directive instead:

#deprecated "Use ActionV2"
op Action<Result>(): Result;

@discriminator

Specify the property to be used to discriminate this type.

@discriminator(propertyName: valueof string)

Target

Model | Union

Parameters

NameTypeDescription
propertyNamevalueof stringThe property name to use for discrimination

Examples

@discriminator("kind")
union Pet{ cat: Cat, dog: Dog }

model Cat {kind: "cat", meow: boolean}
model Dog {kind: "dog", bark: boolean}
@discriminator("kind")
model Pet{ kind: string }

model Cat extends Pet {kind: "cat", meow: boolean}
model Dog extends Pet {kind: "dog", bark: boolean}

@doc

Attach a documentation string.

@doc(doc: valueof string, formatArgs?: {})

Target

unknown

Parameters

NameTypeDescription
docvalueof stringDocumentation string
formatArgs{}Record with key value pair that can be interpolated in the doc.

Examples

@doc("Represent a Pet available in the PetStore")
model Pet {}

@encode

Specify how to encode the target type.

@encode(encoding: string | EnumMember, encodedAs?: Scalar)

Target

Scalar | ModelProperty

Parameters

NameTypeDescription
encodingstring | EnumMemberKnown name of an encoding.
encodedAsScalarWhat target type is this being encoded as. Default to string.

Examples

offsetDateTime encoded with rfc7231
@encode("rfc7231")
scalar myDateTime extends offsetDateTime;
utcDateTime encoded with unixTimestamp
@encode("unixTimestamp", int32)
scalar myDateTime extends unixTimestamp;

@encodedName

Provide an alternative name for this type when serialized to the given mime type.

@encodedName(mimeType: valueof string, name: valueof string)

Target

unknown

Parameters

NameTypeDescription
mimeTypevalueof stringMime type this should apply to. The mime type should be a known mime type as described here https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types without any suffix (e.g. +json)
namevalueof stringAlternative name

Examples

model Certificate {
@encodedName("application/json", "exp")
@encodedName("application/xml", "expiry")
expireAt: int32;
}
Invalid values
@encodedName("application/merge-patch+json", "exp")
^ error cannot use subtype

@error

Specify that this model is an error type. Operations return error types when the operation has failed.

@error

Target

Model

Parameters

None

Examples

@error
model PetStoreError {
code: string;
message: string;
}

@errorsDoc

Attach a documentation string to describe the error return types of an operation. If an operation returns a union of success and errors it only describe the errors. See @errorsDoc for success documentation.

@errorsDoc(doc: valueof string)

Target

Operation

Parameters

NameTypeDescription
docvalueof stringDocumentation string

Examples

@errorsDoc("Returns doc")
op get(): Pet | NotFound;

@format

Specify a known data format hint for this string type. For example uuid, uri, etc. This differs from the @pattern decorator which is meant to specify a regular expression while @format accepts a known format name. The format names are open ended and are left to emitter to interpret.

@format(format: valueof string)

Target

string | bytes | ModelProperty

Parameters

NameTypeDescription
formatvalueof stringformat name.

Examples

@format("uuid")
scalar uuid extends string;

@friendlyName

Specifies how a templated type should name their instances.

@friendlyName(name: valueof string, formatArgs?: unknown)

Target

unknown

Parameters

NameTypeDescription
namevalueof stringname the template instance should take
formatArgsunknownModel with key value used to interpolate the name

Examples

@friendlyName("{name}List", T)
model List<Item> {
value: Item[];
nextLink: string;
}

@inspectType

A debugging decorator used to inspect a type.

@inspectType(text: valueof string)

Target

unknown

Parameters

NameTypeDescription
textvalueof stringCustom text to log

@inspectTypeName

A debugging decorator used to inspect a type name.

@inspectTypeName(text: valueof string)

Target

unknown

Parameters

NameTypeDescription
textvalueof stringCustom text to log

@key

Mark a model property as the key to identify instances of that type

@key(altName?: valueof string)

Target

ModelProperty

Parameters

NameTypeDescription
altNamevalueof stringName of the property. If not specified, the decorated property name is used.

Examples

model Pet {
@key id: string;
}

@knownValues

Provide a set of known values to a string type.

@knownValues(values: Enum)

Target

string | numeric | ModelProperty

Parameters

NameTypeDescription
valuesEnumKnown values enum.

Examples

@knownValues(KnownErrorCode)
scalar ErrorCode extends string;

enum KnownErrorCode {
NotFound,
Invalid,
}

@list

Mark this operation as a list operation for resource types.

@list(listedType?: Model)

Target

Operation

Parameters

NameTypeDescription
listedTypeModelOptional type of the items in the list.

@maxItems

Specify the maximum number of items this array should have.

@maxItems(value: valueof integer)

Target

unknown[] | ModelProperty

Parameters

NameTypeDescription
valuevalueof integerMaximum number

Examples

@maxItems(5)
model Endpoints is string[];

@maxLength

Specify the maximum length this string type should be.

@maxLength(value: valueof integer)

Target

string | ModelProperty

Parameters

NameTypeDescription
valuevalueof integerMaximum length

Examples

@maxLength(20)
scalar Username extends string;

@maxValue

Specify the maximum value this numeric type should be.

@maxValue(value: valueof numeric)

Target

numeric | ModelProperty

Parameters

NameTypeDescription
valuevalueof numericMaximum value

Examples

@maxValue(200)
scalar Age is int32;

@maxValueExclusive

Specify the maximum value this numeric type should be, exclusive of the given value.

@maxValueExclusive(value: valueof numeric)

Target

numeric | ModelProperty

Parameters

NameTypeDescription
valuevalueof numericMaximum value

Examples

@maxValueExclusive(50)
scalar distance is float64;

@minItems

Specify the minimum number of items this array should have.

@minItems(value: valueof integer)

Target

unknown[] | ModelProperty

Parameters

NameTypeDescription
valuevalueof integerMinimum number

Examples

@minItems(1)
model Endpoints is string[];

@minLength

Specify the minimum length this string type should be.

@minLength(value: valueof integer)

Target

string | ModelProperty

Parameters

NameTypeDescription
valuevalueof integerMinimum length

Examples

@minLength(2)
scalar Username extends string;

@minValue

Specify the minimum value this numeric type should be.

@minValue(value: valueof numeric)

Target

numeric | ModelProperty

Parameters

NameTypeDescription
valuevalueof numericMinimum value

Examples

@minValue(18)
scalar Age is int32;

@minValueExclusive

Specify the minimum value this numeric type should be, exclusive of the given value.

@minValueExclusive(value: valueof numeric)

Target

numeric | ModelProperty

Parameters

NameTypeDescription
valuevalueof numericMinimum value

Examples

@minValueExclusive(0)
scalar distance is float64;

@overload

Specify this operation is an overload of the given operation.

@overload(overloadbase: Operation)

Target

Operation

Parameters

NameTypeDescription
overloadbaseOperationBase operation that should be a union of all overloads

Examples

op upload(data: string | bytes, @header contentType: "text/plain" | "application/octet-stream"): void;
@overload(upload)
op uploadString(data: string, @header contentType: "text/plain" ): void;
@overload(upload)
op uploadBytes(data: bytes, @header contentType: "application/octet-stream"): void;

@parameterVisibility

Sets which visibilities apply to parameters for the given operation.

@parameterVisibility(...visibilities: valueof string[])

Target

Operation

Parameters

NameTypeDescription
visibilitiesvalueof string[]List of visibility strings which apply to this operation.

@pattern

Specify the the pattern this string should respect using simple regular expression syntax. The following syntax is allowed: alternations (|), quantifiers (?, *, +, and { }), wildcard (.), and grouping parentheses. Advanced features like look-around, capture groups, and references are not supported.

This decorator may optionally provide a custom validation message. Emitters may choose to use the message to provide context when pattern validation fails. For the sake of consistency, the message should be a phrase that describes in plain language what sort of content the pattern attempts to validate. For example, a complex regular expression that validates a GUID string might have a message like "Must be a valid GUID."

@pattern(pattern: valueof string, validationMessage?: valueof string)

Target

string | bytes | ModelProperty

Parameters

NameTypeDescription
patternvalueof stringRegular expression.
validationMessagevalueof stringOptional validation message that may provide context when validation fails.

Examples

@pattern("[a-z]+", "Must be a string consisting of only lower case letters and of at least one character.")
scalar LowerAlpha extends string;

@projectedName

DEPRECATED: Use @encodedName instead.

Provide an alternative name for this type.

@projectedName(targetName: valueof string, projectedName: valueof string)

Target

unknown

Parameters

NameTypeDescription
targetNamevalueof stringProjection target
projectedNamevalueof stringAlternative name

Examples

model Certificate {
@projectedName("json", "exp")
expireAt: int32;
}

@returnsDoc

Attach a documentation string to describe the successful return types of an operation. If an operation returns a union of success and errors it only describe the success. See @errorsDoc for error documentation.

@returnsDoc(doc: valueof string)

Target

Operation

Parameters

NameTypeDescription
docvalueof stringDocumentation string

Examples

@returnsDoc("Returns doc")
op get(): Pet | NotFound;

@returnTypeVisibility

Sets which visibilities apply to the return type for the given operation.

@returnTypeVisibility(...visibilities: valueof string[])

Target

Operation

Parameters

NameTypeDescription
visibilitiesvalueof string[]List of visibility strings which apply to this operation.

@secret

Mark this string as a secret value that should be treated carefully to avoid exposure

@secret

Target

string | ModelProperty

Parameters

None

Examples

@secret
scalar Password is string;

@service

Mark this namespace as describing a service and configure service properties.

@service(options?: ServiceOptions)

Target

Namespace

Parameters

NameTypeDescription
optionsServiceOptionsOptional configuration for the service.

Examples

@service
namespace PetStore;
Setting service title
@service({title: "Pet store"})
namespace PetStore;
Setting service version
@service({version: "1.0"})
namespace PetStore;

@summary

Typically a short, single-line description.

@summary(summary: valueof string)

Target

unknown

Parameters

NameTypeDescription
summaryvalueof stringSummary string.

Examples

@summary("This is a pet")
model Pet {}

@tag

Attaches a tag to an operation, interface, or namespace. Multiple @tag decorators can be specified to attach multiple tags to a TypeSpec element.

@tag(tag: valueof string)

Target

Namespace | Interface | Operation

Parameters

NameTypeDescription
tagvalueof stringTag value

@visibility

Indicates that a property is only considered to be present or applicable ("visible") with the in the given named contexts ("visibilities"). When a property has no visibilities applied to it, it is implicitly visible always.

As far as the TypeSpec core library is concerned, visibilities are open-ended and can be arbitrary strings, but the following visibilities are well-known to standard libraries and should be used with standard emitters that interpret them as follows:

  • "read": output of any operation.
  • "create": input to operations that create an entity..
  • "query": input to operations that read data.
  • "update": input to operations that update data.
  • "delete": input to operations that delete data.

See also: Automatic visibility

@visibility(...visibilities: valueof string[])

Target

ModelProperty

Parameters

NameTypeDescription
visibilitiesvalueof string[]List of visibilities which apply to this property.

Examples

model Dog {
// the service will generate an ID, so you don't need to send it.
@visibility("read") id: int32;
// the service will store this secret name, but won't ever return it
@visibility("create", "update") secretName: string;
// the regular name is always present
name: string;
}

@withDefaultKeyVisibility

Set the visibility of key properties in a model if not already set.

@withDefaultKeyVisibility(visibility: valueof string)

Target

Model

Parameters

NameTypeDescription
visibilityvalueof stringThe desired default visibility value. If a key property already has a visibility decorator then the default visibility is not applied.

@withOptionalProperties

Returns the model with required properties removed.

@withOptionalProperties

Target

Model

Parameters

None

@withoutDefaultValues

Returns the model with any default values removed.

@withoutDefaultValues

Target

Model

Parameters

None

@withoutOmittedProperties

Returns the model with the given properties omitted.

@withoutOmittedProperties(omit: string | Union)

Target

Model

Parameters

NameTypeDescription
omitstring | UnionList of properties to omit

@withUpdateableProperties

Returns the model with non-updateable properties removed.

@withUpdateableProperties

Target

Model

Parameters

None

@withVisibility

Removes properties that are not considered to be present or applicable ("visible") in the given named contexts ("visibilities"). Can be used together with spread to effectively spread only visible properties into a new model.

See also: Automatic visibility

When using an emitter that applies visibility automatically, it is generally not necessary to use this decorator.

@withVisibility(...visibilities: valueof string[])

Target

Model

Parameters

NameTypeDescription
visibilitiesvalueof string[]List of visibilities which apply to this property.

Examples

model Dog {
@visibility("read") id: int32;
@visibility("create", "update") secretName: string;
name: string;
}

// The spread operator will copy all the properties of Dog into DogRead,
// and @withVisibility will then remove those that are not visible with
// create or update visibility.
//
// In this case, the id property is removed, and the name and secretName
// properties are kept.
@withVisibility("create", "update")
model DogCreateOrUpdate {
...Dog;
}

// In this case the id and name properties are kept and the secretName property
// is removed.
@withVisibility("read")
model DogRead {
...Dog;
}