Логотип Typescript Best Practices

Typescript Best Practices

Организация
overextended
typescript-best-practices

TypeScript best practices for FiveM resources and their NUI. Use when reading or editing any .ts or .tsx file or a .svelte file with <script lang="ts">, or when the user asks how to type net events, callbacks, exports, NUI messages or state bags.

Обзор

Издательoverextended
Репозиторийskills
Название навыкаtypescript-best-practices
Звёзды
22
Форки
4
Встроенные файлы
3
ЛицензияGPL-3.0
Ссылки
  • Инструкции в формате Markdown

    Файл SKILL.md, который модель загружает по необходимости, поэтому токены расходуются только при подходящем запросе.

  • Работает с любой языковой моделью

    Навыки ИИ — это обычный Markdown, а не код для конкретного поставщика, поэтому они работают с GPT, Claude, Gemini, Grok и локальными моделями.

  • Файлы в комплекте: 3

    Скрипты, шаблоны и справочные материалы, которые модель может читать во время работы. Файлы доступны только для чтения и никогда не выполняются.

  • Открытый исходный код

    Опубликовано на GitHub: overextended. Перед установкой изучите исходные материалы.

Установка

Установите навык ИИ Typescript Best Practices в TypingMind, чтобы использовать его с любой LLM, или добавьте его в другой агент, который умеет читать SKILL.md.

1

Установка в TypingMind

TypingMind устанавливает навык прямо из его папки на GitHub: читает SKILL.md, собирает файлы ресурсов и сохраняет результат локально.

  1. Откройте приложение и перейдите в раздел «Плагины → Навыки».
  2. Выберите «Установить из GitHub».
  3. Вставьте указанную ниже ссылку на папку навыка и подтвердите установку.
    https://github.com/overextended/skills/tree/main/skills/fivem/typescript-best-practices
  4. Включите навык в каждом чате, где хотите его использовать.
Плагины → Навыки → Новый навык → По ссылке GitHub, затем вставьте ссылку на папку и нажмите «Продолжить».
2

Установка в другом агенте

Любой агент с поддержкой формата Agent Skills может использовать этот навык — скопируйте папку в каталог навыков этого агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/overextended/skills.git /tmp/skills
mkdir -p .claude/skills
cp -r /tmp/skills/skills/fivem/typescript-best-practices .claude/skills/typescript-best-practices
После копирования перезапустите Claude Code, чтобы загрузить новый навык.

Использование в TypingMind

Включите навык Typescript Best Practices в любом чате TypingMind, и дальше модель всё сделает сама. Его название и описание хранятся в системном промпте, а при появлении подходящего запроса модель сама загружает полные инструкции. Вам не нужно вызывать навык вручную, и до фактического использования он не расходует токены.

Модель сама загружает навык Typescript Best Practices, как только появляется подходящий для него запрос.

Работает с любой моделью ИИ

Навыки ИИ — это обычные инструкции в Markdown, а не код для конкретного поставщика, поэтому навык Typescript Best Practices не привязан к модели, для которой он был создан. Установите его один раз в TypingMind и используйте с GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama или локальной моделью, которую запускаете самостоятельно, — со своими API-ключами.

  • Загружается только при необходимости

    Системный промпт содержит только название и описание. Инструкции загружаются при первом подходящем запросе, поэтому неиспользуемый навык не расходует токены.

  • Меняйте модели прямо в чате

    Навык состоит из инструкций, а не кода, поэтому смена модели не нарушает его работу: новая модель читает тот же файл SKILL.md.

Инструкции навыка

Это содержимое файла SKILL.md, которое загружает модель. Прочитайте его перед установкой: навык — это инструкции, которым будет следовать ваша модель.

TypeScript best practices

Make the compiler reject impossible states, mixed-up ids and unhandled variants. In a FiveM resource most of the type safety leaks out at the runtime's edges: onNet, exports, state bags and NUI callbacks are typed any or Function, so a type annotation there is a cast that nothing checks. Parse at those edges and trust the types everywhere else.

Principles

  • Make illegal states unrepresentable. If you can write a comment explaining when a combination of fields is valid, split it into a discriminated union.
  • Build types, don't restrict them. Choose the shape that can't hold the illegal value (a head plus a rest, a start plus a duration) instead of a loose type plus runtime checks.
  • Don't lie to the compiler. If it can't prove a fact, prove it (validate, narrow, remodel). Trace every any, as and ! to the boundary and validate there.
  • Strengthen a type only where partiality appears. A !, a cast or a "should never happen" throw marks a type that is too weak. Push that check into the type, then stop.
  • Validate at boundaries, trust inside. Business logic lives in plain functions that take typed data. The event handler around it is thin: parse, call, reply.

Rules

RuleSummary
Discriminated unionsModel variants with a kind literal discriminant so impossible states can't be represented. No optional-field bags.
Branded typesBrand primitives with & { readonly __brand: "X" } so a server id, a character id and an item name can't be mixed up. Validate once at the boundary.
Constructive modelingBuild the shape so the illegal value can't be constructed. [T, ...T[]] for non-empty, [T, T][] for even length, start plus duration for a range.
Simplest total typeKeep T[] while every operation on it stays total. Strengthen to NonEmpty<T> only where the loose type forces !, a cast, or a "should never happen" throw.
unknown over anyData from outside the resource is unknown, including the arguments of net event handlers.
Parse functionsTurn client data into a typed value with a function that takes unknown and returns the value or null (toCoords(value: unknown): Vec3 | null). Reuse the resource's existing parsers and guards before writing a new one. Don't add a schema library: FiveM resources don't use one.
null means omittedFiveM serializes event arguments with MessagePack, which can turn an omitted or undefined value into null. Check optional values with != null, never !== undefined alone, and require values by type and range, not truthiness: 0 and false are valid.
No as castsEvery as is a runtime crash waiting. Cast only after validation. A type argument such as triggerServerCallback<T> is a cast too.
Narrowing hierarchyDiscriminant switch > in operator > typeof/instanceof > user-defined type guard > as.
Type guardsMust verify the claim. A lying guard is worse than as because the bug hides behind a name that says it's safe. Name them isX or hasX.
ExhaustivenessInline const _exhaustive: never = x; in default arms so the compiler errors when a new variant is added.
satisfies over asValidates the value without widening literal types.
Boundary validationParse where data crosses in, into a named domain type. Trust types inside. See FiveM boundaries below.
Derived typesReach for Pick/Omit/Parameters/ReturnType/Awaited/typeof before declaring a new interface. Share one type between the client script and the NUI instead of declaring it twice.
Object argsPass objects, not positional, so argument order is self-documenting. Skip on hot paths (setTick callbacks, anything running every frame) and don't wrap natives just to get object args.
Real testsDon't mock what you can run. Plain logic gets real unit tests when the resource has a runner; natives, events and NUI are verified on a running server.
Useful logsLog with enough context to debug from an id: player id, event name, resource. No debug console.log left in shipped code.

FiveM boundaries

Every one of these is data the compiler knows nothing about. Parse it where it arrives:

BoundaryWhy it's untyped
onNet handler arguments on the serverAny client can trigger the event with any arguments. onNet takes a Function, so parameter annotations go unchecked.
onClientCallback arguments (@overextended/ox_lib/server)Typed ...args: any[], and they come from a client.
RegisterNuiCallback dataComes from the browser, which the player can drive with devtools. The server re-checks anything the client forwards to it.
exports.<resource>.<name>() resultsEvery export is typed Function, so its result is any. Wrap it once in a typed function.
State bags (GlobalState, Player(id).state, Entity(id).state)Indexed as any. Treat a key a client can write as client data.
triggerServerCallback<T> replies (@overextended/ox_lib/client)T is not checked, and the return type is Promise<T> | void: it resolves to nothing when its delay rate limit drops the call.
JSON.parse, KVP strings, convars, database rows, item metadataStrings or untyped rows. Persisted JSON gets a version field and a try / catch around the parse.

On the server, copy source into a local at the top of every handler, before any await: it is a global that the next event overwrites.

When the resource uses ox_lib from TypeScript, import @overextended/ox_lib instead of calling exports.ox_lib directly: the package wraps the exports with types.

Examples

Read PATTERNS.md for a code example of each rule.

Встроенные файлы

Модель читает эти файлы по мере необходимости, пока навык загружен. Они доступны только для чтения и никогда не выполняются.

Часто задаваемые вопросы

Что делает навык ИИ Typescript Best Practices?

TypeScript best practices for FiveM resources and their NUI. Use when reading or editing any .ts or .tsx file or a .svelte file with <script lang="ts">, or when the user asks how to type net events, callbacks, exports, NUI messages or state bags.

Зачем использовать Typescript Best Practices в TypingMind?

Потому что вы устанавливаете навык один раз и используете его с любой моделью. Typescript Best Practices — это обычный текст в формате Markdown, а не код для конкретного поставщика, поэтому один и тот же навык работает с GPT-5, Claude, Gemini, Grok или локальной моделью. Вы можете менять модель прямо во время чата, и навык продолжит работать. TypingMind использует ваши собственные ключи API, поэтому вы платите поставщикам напрямую, а не оформляете подписку с оплатой за каждое место. Ваши навыки и чаты остаются в вашем собственном хранилище.

Как установить Typescript Best Practices в TypingMind?

В TypingMind откройте «Плагины → Навыки → Установить из GitHub» и вставьте https://github.com/overextended/skills/tree/main/skills/fivem/typescript-best-practices. TypingMind прочитает файл SKILL.md, включит сопутствующие файлы в пакет и установит навык, который можно включать отдельно для каждого чата.

Какие модели ИИ могут использовать Typescript Best Practices?

Любая модель, которую вы подключите в TypingMind. Навыки ИИ — это обычные инструкции в формате Markdown, а не код для конкретного поставщика, поэтому GPT, Claude, Gemini, Grok и локальные модели могут загружать этот навык, когда запрос ему соответствует.

Со сколькими моделями ИИ можно использовать Typescript Best Practices?

С любым количеством. Если модель поддерживает навыки, вы можете использовать с ней Typescript Best Practices: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama и другие — всё в TypingMind с вашими собственными ключами API.

Бесплатен ли навык ИИ Typescript Best Practices?

Да. Навык опубликован на GitHub автором overextended по лицензии GPL-3.0. Вы платите только своему поставщику ИИ за использованные токены.

Что такое навыки ИИ?

Навык ИИ — это многоразовый набор инструкций, который объясняет модели ИИ, как выполнять конкретную задачу. Он соответствует открытому формату Agent Skills: файл SKILL.md с названием и описанием, а также любые скрипты, шаблоны или справочные файлы, которые могут понадобиться модели. Модель читает инструкции, только когда ваш запрос соответствует навыку, поэтому установленный навык ничего не стоит, пока не используется.

Чем навыки ИИ отличаются от плагинов и серверов MCP?

Плагин или сервер MCP даёт модели новые инструменты для вызова — код, который где-то выполняется и возвращает результат. Навык ИИ вместо этого даёт модели знания и порядок действий: как подойти к задаче, какие шаги выполнить и каким должен быть хороший результат. Навыки — это обычный текст в формате Markdown, поэтому им не нужны сервер, ключ API или среда выполнения, и они работают с любой моделью.

Все

Создайте свою рабочую ИИ-среду сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇