TypeScript
Node oluşturma
ts.factory ile AST düğümü üretmeyi öğrenirsin.
ts.factory nedir?
ts.factory, TypeScript derleyicisinde yeni AST düğümleri üreten nesnedir. createIdentifier, createNumericLiteral, createStringLiteral gibi yöntemleri her tür düğüm için içerir. Eski ts.createNode tarzı API'nin yerini almıştır.
const id = ts.factory.createIdentifier("merhaba");
const num = ts.factory.createNumericLiteral("42");
const str = ts.factory.createStringLiteral("selam");
Üretilen düğümler transformer içinde veya elle kurulan AST'lerde kullanılır.
Düğüm birleştirme
Düğümleri birleştirerek kompleks ifadeler kurarsın. Örneğin console.log(42) için: createPropertyAccessExpression ile console.log, createCallExpression ile çağrı, createExpressionStatement ile deyim üretirsin.
const call = ts.factory.createCallExpression(
ts.factory.createPropertyAccessExpression(
ts.factory.createIdentifier("console"),
ts.factory.createIdentifier("log")
),
undefined,
[ts.factory.createNumericLiteral("42")]
);
Uygulama console.log(42) düğümü kur
ts.factory ile console.log(42) ifadesini kur: PropertyAccessExpression ile console.log, CallExpression ile çağrı, ExpressionStatement ile deyim üret. Sonucu ts.createPrinter ve printNode ile yazdır.
Örnek çözümü göster
import ts from "typescript";
const dummy = ts.createSourceFile("dummy.ts", "", ts.ScriptTarget.Latest, true);
const call = ts.factory.createCallExpression(
ts.factory.createPropertyAccessExpression(
ts.factory.createIdentifier("console"),
ts.factory.createIdentifier("log")
),
undefined,
[ts.factory.createNumericLiteral("42")]
);
const stmt = ts.factory.createExpressionStatement(call);
const printer = ts.createPrinter();
console.log(printer.printNode(ts.EmitHint.Unspecified, stmt, dummy));
Kendini test et
-
ts.factory.createIdentifier("x") ne döndürür?
- Bir Identifier düğümü
- Bir Symbol nesnesi
- Bir string değer
- Bir Type nesnesi
Cevabı göster
Bir Identifier düğümü — createIdentifier yeni bir Identifier AST düğümü döndürür; string, Type veya Symbol değil.
-
Sayısal düğüm üret
const num = ts.factory.____("42");
Cevabı göster
const num = ts.factory.createNumericLiteral("42");
-
factory parçaları
- ts.factory.createIdentifier
- Identifier düğümü üretir
- ts.factory.createNumericLiteral
- NumericLiteral düğümü üretir
- ts.factory.createCallExpression
- Çağrı ifadesi üretir
- ts.factory.createExpressionStatement
- Deyim üretir
Sıradaki ders: Custom transformer