typescript

Utilisez ce guide lorsque vous travaillez sur des modifications TypeScript dans le monorepo FAST — création de composants Web, rédaction de modèles et de styles, travail avec le…

npx skills add https://github.com/microsoft/fast --skill typescript

TypeScript Patterns for FAST

Modules

fast-element enables verbatimModuleSyntax, so type-only imports must use import type or the inline type qualifier:

import type { Notifier, Subscriber } from "./notifier.js";
import { type Constructable, isFunction } from "../interfaces.js";

Sub-entry-points expose focused APIs through the exports map:

import { twoWay } from "@microsoft/fast-element/two-way.js";
import { reactive } from "@microsoft/fast-element/state.js";

The barrel index.ts explicitly lists every re-export grouped by subsystem — no export * statements.

Aside from the index.ts or index.*.ts files there should be no barrel exports.

Side Effects

Do not add side effectful code and do not add sideEffects to package.json files. APIs added should import named exports.

Browser APIs

Do not use

Our stance as a framework library is that certain browser APIs are best avoided by the framework. We may facilitate the use of them through our provided APIs.

List of APIs to avoid implementing in FAST packages:

  • requestIdleCallback
  • setTimeout
  • setInterval

Avoid

Some browser APIs can be used but should be avoided as a developer may encounter edge cases with task queuing or other logic their app is executing.

List of APIs to avoid in FAST packages:

  • requestAnimationFrame
  • queueMicrotask

Custom elements

Elements extend FASTElement. Do not use the @customElement decorator.

Use define() for registration. define() returns a Promise that resolves immediately when a template is provided:

Example define.ts (side-effect import):

export class MyElement extends FASTElement {
    @observable items: string[] = [];
}

await MyElement.define({
    name: "my-element",
    template,
    styles,
});

Templates

Templates use the html tagged template literal typed to the element class:

import { html } from "@microsoft/fast-element/html.js";
import { repeat } from "@microsoft/fast-element/repeat.js";
import { when } from "@microsoft/fast-element/when.js";
import type { MyElement } from "./my-element.js";

export const template = html<MyElement>`
    <h1>${x => x.title}</h1>
    ${when(x => x.showList, html<MyElement>`
        <ul>
            ${repeat(
                x => x.items,
                html<string>`<li>${x => x}</li>`
            )}
        </ul>
    `)}
`;

Binding syntax

PrefixPurposeExample
${x => ...}Content or attribute${x => x.name}
@eventEvent listener@click=${x => x.handleClick()}
@eventEvent with context@click=${(x, c) => c.parent.remove(x)}
:propDOM property:value=${twoWay(x => x.description)}
?attrBoolean attribute?disabled=${x => !x.isValid}

Two-way bindings require a sub-entry-point import:

import { twoWay } from "@microsoft/fast-element/two-way.js";

Partial HTML

Use html.partial() to inject pre-built HTML strings into a template without creating a full ViewTemplate:

html<MyElement>`
    <div>${html.partial("<span>static markup</span>")}</div>
`;

Styles

Styles use the css tagged template literal. They attach through the element definition's styles property:

import { css } from "@microsoft/fast-element/css.js";

export const styles = css`
    :host {
        display: block;
        padding: 16px;
    }
`;

For declarative HTML definitions, styles live in a separate .styles.css file linked from both the initial shadow root template and the <f-template>:

<f-template name="my-element">
    <template>
        <link rel="stylesheet" href="./my-element.styles.css">
    </template>
</f-template>

css.partial() works the same way as html.partial() — injecting raw CSS strings.

Reactivity

@attr maps HTML attributes to properties. @observable creates reactive properties tracked by templates. @volatile marks getters whose dependencies change between calls:

import { FASTElement } from "@microsoft/fast-element/fast-element.js";
import { attr, nullableNumberConverter } from "@microsoft/fast-element/attr.js";
import { Observable, observable } from "@microsoft/fast-element/observable.js";
import { volatile } from "@microsoft/fast-element/volatile.js";

class MyElement extends FASTElement {
    @attr label?: string;
    @attr({ mode: "boolean" }) active?: boolean;
    @attr({ converter: nullableNumberConverter }) count?: number;

    @observable private _items: string[] = [];

    // Convention: ${propertyName}Changed
    labelChanged(prev: string | undefined, next: string | undefined) {}

    @volatile
    get sortedItems(): readonly string[] {
        return [...this._items].sort();
    }
}

Notify the system after in-place mutations that it cannot detect automatically:

this._items.splice(index, 1);
Observable.notify(this, "_items");

Make plain objects observable via the state sub-entry-point:

import { reactive } from "@microsoft/fast-element/state.js";
const todo = reactive({ description: "Buy milk", done: false });

Testing

Tests use Playwright Test (*.pw.spec.ts) and combine two patterns within the same file.

Direct-import tests

For logic that does not need browser APIs — the test callback takes no parameters:

import { expect, test } from "@playwright/test";
import { Observable } from "./observable.js";

test.describe("Observable", () => {
    test("can get a notifier", () => {
        const notifier = Observable.getNotifier(new Model());
        expect(notifier).toBeInstanceOf(PropertyChangeNotifier);
    });
});

Browser-evaluated tests

For tests requiring DOM APIs, navigate to the Vite dev server and import via "/main.js". The @ts-expect-error comment is required because TypeScript cannot resolve the URL-based import:

test("renders element", async ({ page }) => {
    await page.goto("/");

    const result = await page.evaluate(async () => {
        // @ts-expect-error: Client module.
        const { FASTElement, html, uniqueElementName } = await import("/main.js");
        // ... test logic ...
        return someSerializableValue;
    });

    expect(result).toBe(expected);
});

Only serializable values can cross the page.evaluate boundary — run expect() assertions outside it on the returned data.

The test harness at packages/<package>/test/main.ts re-exports source modules for browser tests. When adding new package exports, add them there too.

TypeScript idioms

Const-type merging for enumerations

Frozen const objects paired with a type extracted from their values replace TypeScript enum:

export const SourceLifetime = {
    default: undefined,
    couple: 1,
} as const;

export type SourceLifetime =
    (typeof SourceLifetime)[keyof typeof SourceLifetime];

Interface-const merging

FASTElement is both an interface (instance shape) and a const (constructor). Static methods use typeof to carry overloaded signatures:

export const FASTElement: {
    new (): FASTElement;
    define: typeof define;
} = Object.assign(createFASTElement(HTMLElement), { define });

Tagged template intersection types

html and css are typed as intersections of a tagged template function and a .partial() method:

type HTMLTemplateTag = (<TSource, TParent>(
    strings: TemplateStringsArray,
    ...values: TemplateValue<TSource, TParent>[]
) => ViewTemplate<TSource, TParent>) & {
    partial(html: string): InlineTemplateDirective;
};

Plus de skills de microsoft

oss-growth
microsoft
Persona de growth hacker OSS
agent-framework-azure-ai-py
microsoft
Créez des agents Azure AI Foundry à l’aide du SDK Python Microsoft Agent Framework (agent-framework-azure-ai). À utiliser lors de la création d’agents persistants avec AzureAIAgentsProvider, de l’utilisation d’outils hébergés (interpréteur de code, recherche de fichiers, recherche web), de l’intégration de serveurs MCP, de la gestion de fils de conversation ou de l’implémentation de réponses en streaming. Couvre les outils de fonction, les sorties structurées et les agents multi-outils.
development
airunway-aks-setup
microsoft
Configurez AI Runway sur AKS — du cluster nu au modèle en cours d'exécution. Couvre la vérification du cluster, l'installation du contrôleur, l'évaluation GPU, la configuration du fournisseur et le premier déploiement. QUAND : « configurer AI Runway », « intégrer un cluster AKS », « installer AI Runway », « configuration airunway », « déployer un modèle sur AKS », « inférence GPU sur AKS », « configuration KAITO sur AKS », « exécuter LLM sur AKS », « vLLM sur AKS », « configurer le service de modèles sur AKS », « contrôleur AI Runway ».
devops
appinsights-instrumentation
microsoft
Conseils pour instrumenter les applications web avec Azure Application Insights. Fournit des modèles de télémétrie, la configuration du SDK et des références de configuration. QUAND : comment instrumenter une application, SDK App Insights, modèles de télémétrie, qu'est-ce qu'App Insights, conseils sur Application Insights, exemples d'instrumentation, bonnes pratiques APM.
devops
applicationinsights-web-ts
microsoft
Instrumentez les applications navigateur/web avec le SDK JavaScript Application Insights (@microsoft/applicationinsights-web). Utilisez-le pour la surveillance des utilisateurs réels (RUM) — vues de page, clics, dépendances AJAX/fetch, exceptions, événements personnalisés et traces d’agents GenAI côté navigateur corrélées aux traces OpenTelemetry backend. Couvre le script de chargement du SDK et la configuration npm, les extensions de framework (React, React Native, Angular), Click Analytics, les initialiseurs de télémétrie et les conventions sémantiques OTel GenAI pour les spans d’agents/outils/modèles émises depuis le navigateur.
devops
azure-ai-anomalydetector-java
microsoft
Créez des applications de détection d'anomalies avec le SDK Azure AI Anomaly Detector pour Java. Utilisez-le lors de l'implémentation de la détection d'anomalies univariées/multivariées, de l'analyse de séries temporelles ou de la surveillance basée sur l'IA.
development
azure-ai-language-conversations-py
microsoft
Implémentez la compréhension du langage conversationnel (CLU) à l’aide du SDK Python azure-ai-language-conversations. Utilisez-le lorsque vous travaillez avec ConversationAnalysisClient pour analyser l’intention et les entités d’une conversation, créer des fonctionnalités de NLP ou intégrer la compréhension du langage dans des applications.
development
azure-ai-ml-py
microsoft
SDK v2 d’Azure Machine Learning pour Python. Utiliser pour les espaces de travail ML, les tâches, les modèles, les jeux de données, le calcul et les pipelines. Déclencheurs : « azure-ai-ml », « MLClient », « espace de travail », « registre de modèles », « tâches d’entraînement », « jeux de données ».
development