Ensure data consistency
Benefit from the reusability and modularity of TypeSpec types to ensure data consistency across your APIs.
Get started
import "./common.tsp";
namespace MyOrg.Accounts;
using MyOrg.Types;
model Account {
id: id;
firstName: string;
lastName: string;
createdAt: utcDateTime;
// Use imported type by name only when using `using`
ssn: ssn;
// Or use the fully qualified name
email: MyOrg.Types.email;
balance: Amount;
}
model Amount {
value: decimal128;
currency: Currency;
}
// Create your own error types by extending the Error type
model AccountError is Error<"duplicate-account" | "invalid-account">;
op createAccount(account: Account): Account;
op charge(accountId: id, amount: Amount): void | AccountError;
Standard library
Use built-in decorators
TypeSpec standard library provides decorators for common validation patterns.
Standard library reference
Browse the standard library reference documentation for details.
Learn more →
model User {
@minLength(3)
@maxLength(50)
username: string;
@secret
password: string;
@minValue(0)
@maxValue(200)
age: uint32;
@minItems(1)
@maxItems(10)
emails: string[];
}
@pattern(".+\\@.+\\..+")
scalar email extends string;
Output
Produce JSON Schema
Benefit from the JSON Schema ecosystem to validate your data while writing more concise and readable code.
Configure the JSON schema emitter
Change how the JSON schema is emitted: specify a bundleId to combine all schemas into a single file or use JSON instead of yaml.
Learn more →
import "@typespec/json-schema";
using TypeSpec.JsonSchema;
@jsonSchema
namespace Schemas;
model Person {
/** The person's full name. */
name: string;
/** Person address */
address: Address;
/** List of nick names */
@uniqueItems nickNames?: string[];
/** List of cars person owns */
cars?: Car[];
}
/** Respresent an address */
model Address {
street: string;
city: string;
country: string;
}
model Car {
/** Kind of car */
kind: "ev" | "ice";
/** Brand of the car */
brand: string;
/** Year the car was manufactured. */
@minValue(1900) year: int32;
}
Customize
JSON Schema Decorators
The JSON schema library provides decorators to customize the output with JSON schema specific concepts.
JSON Schema Decorators Reference
Read the reference documentation for available options.
Learn more →
import "@typespec/json-schema";
using TypeSpec.JsonSchema;
@jsonSchema
@extension(
"x-tag",
Json<{
validate: true,
category: "users",
}>
)
model Server {
@format("hostname")
hostname: string;
}