typescript

작성자: microsoft

FAST 모노레포에서 TypeScript 변경 작업 시 — 웹 컴포넌트 작성, 템플릿 및 스타일 작업, 그리고…

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;
};

microsoft의 다른 스킬

oss-growth
microsoft
OSS 성장 해커 페르소나
agent-framework-azure-ai-py
microsoft
Microsoft Agent Framework Python SDK(agent-framework-azure-ai)를 사용하여 Azure AI Foundry 에이전트를 구축합니다. AzureAIAgentsProvider로 지속적 에이전트를 만들 때, 호스팅 도구(코드 인터프리터, 파일 검색, 웹 검색)를 사용할 때, MCP 서버를 통합할 때, 대화 스레드를 관리할 때, 또는 스트리밍 응답을 구현할 때 사용합니다. 함수 도구, 구조화된 출력, 다중 도구 에이전트를 다룹니다.
development
airunway-aks-setup
microsoft
AKS에서 AI Runway 설정 — 빈 클러스터에서 실행 중인 모델까지. 클러스터 검증, 컨트롤러 설치, GPU 평가, 공급자 설정, 첫 배포를 다룹니다. 시기: "AI Runway 설정", "AKS 클러스터 온보딩", "AI Runway 설치", "airunway 설정", "AKS에 모델 배포", "AKS에서 GPU 추론", "AKS에서 KAITO 설정", "AKS에서 LLM 실행", "AKS에서 vLLM", "AKS에서 모델 서빙 설정", "AI Runway 컨트롤러".
devops
appinsights-instrumentation
microsoft
Azure Application Insights로 웹앱을 계측하기 위한 지침입니다. 원격 분석 패턴, SDK 설정, 구성 참조를 제공합니다. WHEN: 앱 계측 방법, App Insights SDK, 원격 분석 패턴, App Insights란 무엇인가, Application Insights 지침, 계측 예시, APM 모범 사례.
devops
applicationinsights-web-ts
microsoft
브라우저/웹 앱을 Application Insights JavaScript SDK(@microsoft/applicationinsights-web)로 계측합니다. Real User Monitoring(RUM) — 페이지 뷰, 클릭, AJAX/fetch 종속성, 예외, 사용자 지정 이벤트, 백엔드 OpenTelemetry 트레이스와 상관관계가 있는 브라우저 측 GenAI 에이전트 트레이스에 사용합니다. SDK Loader Script 및 npm 설정, 프레임워크 확장(React, React Native, Angular), Click Analytics, 텔레메트리 이니셜라이저, 브라우저에서 생성된 에이전트/도구/모델 스팬에 대한 OTel GenAI 의미론적 규칙을 다룹니다.
devops
azure-ai-anomalydetector-java
microsoft
Azure AI Anomaly Detector SDK for Java로 이상 탐지 애플리케이션을 구축하세요. 단변량/다변량 이상 탐지, 시계열 분석 또는 AI 기반 모니터링을 구현할 때 사용하세요.
development
azure-ai-language-conversations-py
microsoft
azure-ai-language-conversations Python SDK를 사용하여 대화형 언어 이해(CLU)를 구현합니다. ConversationAnalysisClient로 대화 의도와 엔터티를 분석하거나, NLP 기능을 구축하거나, 애플리케이션에 언어 이해를 통합할 때 사용합니다.
development
azure-ai-ml-py
microsoft
Azure Machine Learning SDK v2 for Python. ML 작업 영역, 작업, 모델, 데이터 세트, 컴퓨팅 및 파이프라인에 사용합니다. 트리거: "azure-ai-ml", "MLClient", "workspace", "model registry", "training jobs", "datasets".
development