Kurz-Antwort
• Dekoratoren (@xy) funktionieren in TypeScript momentan nur auf Klassen, Klassen-Eigenschaften, Methoden, Getter/Setter und Parametern – nicht auf type- oder interface-Aliasen.
• Für rein „typische“ Informationen (compile-time) kannst du mit Mapped-/Conditional-Types arbeiten; für zusätzliche Runtime-Metadaten brauchst du Klassen + reflect-metadata oder ein externes Code-Gen-Tool (z. B. Prisma, TypeORM, Zod-Schemas).
──────────────────────────────────────────────
1 ) Dekoratoren: Was geht – was geht nicht?
──────────────────────────────────────────────
✔ Klasse / Property ❯ @Column(), @ID(), …
✘ type / interface-Alias ✯ nicht erlaubt (Syntax-Error)
ts
// ✅ gültig
import 'reflect-metadata';
function ID(): PropertyDecorator {
return (target, key) => {
Reflect.defineMetadata('isId', true, target, key);
};
}
class Group {
@ID() // OK
bookID!: number;
bookLabel!: string;
}
class SQLTest {
@ID() // OK
libID!: number;
libLabel!: string;
group!: Group;
}
ts
// ❌ ungültig
export type SQLTest = {
@ID libID: number // <- SyntaxError: Decorators are not valid here.
}
──────────────────────────────────────────────
2 ) Compile-Time: Typen automatisch „flach“ machen
──────────────────────────────────────────────
Wenn es dir nur um die abgeleitete Result-Form (libID, libLabel, bookID, bookLabel) geht, reicht TypeScript-Magie – ganz ohne Dekorator:
ts
/**
* Rekursive Utility-Types:
* 1. Schlüsselnamen mit Präfix (ParentName)
* 2. Verschachtelung „flatten“
*/
type PrependKeys<Prefix extends string, T> = {
[K in keyof T as `${Prefix}${Capitalize<K & string>}`]: T[K];
};
type Flatten<T> =
{ [K in keyof T as K extends string
? (T[K] extends object ? never : K)
: never]: T[K] } // primitive Felder
& { [K in keyof T as K extends string
? (T[K] extends object ? never : never)
: never]: never } // Trick zur Typ-Verschmelzung
& ({ [K in keyof T]:
T[K] extends object
? PrependKeys<K & string, Flatten<T[K]>>
: unknown }[keyof T]); // rekursiv flatten
// Beispiel-Eingangstyp (ohne Decorators, nur Plain Types)
export type SQLTest = {
libID: number;
libLabel: string;
group: {
bookID: number;
bookLabel: string;
};
};
// Gewünschtes Ergebnis
export type SQLResult = Flatten<SQLTest>;
/**
* ergibt:
* {
* libID: number;
* libLabel: string;
* groupBookID: number;
* groupBookLabel: string;
* }
*/
(Benötigt TS 4.1+ wegen Template-Literal-Types)
──────────────────────────────────────────────
3 ) Runtime-Metadaten (JOIN-Infos, PK, FK, …)
──────────────────────────────────────────────
Sobald du die Infos zur Laufzeit auslesen willst (z. B. PK / FK suchen, automatische SQL-Generierung), brauchst du Klassen-Dekoratoren oder ein Framework:
Option A – DIY + reflect-metadata
ts
import 'reflect-metadata';
function Table(name: string): ClassDecorator {
return target => Reflect.defineMetadata('table', name, target);
}
function Column(name?: string): PropertyDecorator { … }
function ID(): PropertyDecorator { … }
@Table('library')
class Library {
@ID() @Column('libid')
id!: number;
@Column()
label!: string;
}
@Table('book')
class Book {
@ID() @Column('bookid')
id!: number;
@Column()
label!: string;
@Column('libid')
libFK!: number;
}
Mit reflect-metadata kannst du jetzt innerhalb eines Repositories
alle Spalten + Tabelle + PK/FK programmgesteuert auslesen.
Dekoratoren ≠ Type-Alias; wähle Klassen, wenn du Runtime-Infos brauchst.
Für reine Typ-Manipulation genügen Mapped/Conditional-Types (Flatten-Utility).
Falls dir das zu aufwendig ist: setz auf ein bestehendes ORM/Code-Gen-Tool, die lösen PK/FK-Mapping und Join-Ergebnisse out-of-the-box.
User
können die auch sparql ergebnisse umsetzen?
Assistant
Kurzfassung
Die klassischen ORMs (Prisma, TypeORM, MikroORM …) sind auf relationale / dokumentorientierte DBs ausgelegt und verstehen SPARQL nicht. Für RDF-/Triple-Stores brauchst du SPARQL-Clients (z. B. Comunica, rdflib, graphy) oder Middleware wie Ontop / D2RQ, die SQL ↔ RDF mappen. In TypeScript kannst du das Ergebnis-JSON aber sehr leicht in deine eigenen Typen projizieren.
──────────────────────────────────────────────
1 | SPARQL in Node/TypeScript – passende Libs
──────────────────────────────────────────────
• @comunica/actor-init-sparql – Streaming-Abfrage, sehr aktiv gepflegt
• sparql-http-client – simpler Fetch-Wrapper
• rdflib.js – RDF-Library mit SPARQL-Store
• graphy – Low-level Tripel-Lib mit SPARQL-Helpers
• SPARQL.js – Parser/Generator falls du Queries programmatisch bauen willst
In TypeScript you can read the information that a decorator stores in (at least) three different ways:
Immediately, inside the decorator itself
Later, through a side‐table you maintain yourself (a Map, WeakMap, etc.)
Later, through the reflect-metadata API (the de-facto standard way)
Below is a mini “cook-book” that shows all three, points out the caveats (prototype vs. constructor, static vs. instance property, emitDecoratorMetadata, …) and gives you copy-&-paste snippets.
────────────────────────────────────────
0 | Set-up once
────────────────────────────────────────
tsconfig.json (relevant parts):
jsonc
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true, // <- only needed if you want TS-generated design:type etc.
"target": "ES2017",
"module": "commonjs"
}
}
Install the reflect-metadata polyfill (required in Node / browsers):
bash
npm i reflect-metadata
And import it exactly once in your program (e.g. index.ts):
/* ----------------------------------
Decorator definition
-----------------------------------*/
const columnMeta = new WeakMap<any, Record<string, ColumnOptions>>();
interface ColumnOptions {
dbName?: string;
primary?: boolean;
}
export function Column(opts: ColumnOptions = {}): PropertyDecorator {
return (target, key) => {
const meta = columnMeta.get(target) ?? {};
meta[key as string] = opts;
columnMeta.set(target, meta);
};
}
/* ----------------------------------
Usage
-----------------------------------*/
class Book {
@Column({ dbName: 'book_id', primary: true })
id!: number;
@Column({ dbName: 'title' })
title!: string;
}
/* ----------------------------------
Read at runtime
-----------------------------------*/
function getColumns(cls: any) {
// For *instance* properties the metadata is stored on the prototype.
return columnMeta.get(cls.prototype);
}
console.log(getColumns(Book));
/*
{
id: { dbName: 'book_id', primary: true },
title: { dbName: 'title', primary: false }
}
*/
Ergebnis: rows ist ein Array sauber validierter SQLResult-Objekte.
──────────────────────────────────────────────
3 | Generisches Mapping (bindings → beliebiger Typ)
──────────────────────────────────────────────
Willst du ohne Zod einfach automatisch mappen, kannst du einen kleinen Utility-Type schreiben, der die Bindings anhand der Key-Namen castet:
ts
import type * as RDF from '@rdfjs/types';
import { Bindings } from '@comunica/types';
type Primitive = number | string | boolean;
function fromBinding<T extends Record<string, Primitive>>(
b: Bindings,
converters: Partial<Record<keyof T, (v: RDF.Term) => Primitive>> = {},
): T {
const out = {} as T;
for (const key of Object.keys(b) as (keyof T)[]) {
const term = b.get(String(key));
if (!term) continue;
const conv = converters[key];
(out as any)[key] = conv ? conv(term) : term.value;
}
return out;
}
/* usage */
const row = fromBinding<SQLResult>(binding, {
libid: t => +t.value,
bookID: t => +t.value,
});
──────────────────────────────────────────────
4 | SQL ↔ SPARQL Brücken (falls du unbedingt ORM willst)
──────────────────────────────────────────────
• Ontop, D2RQ, Ultrawrap: erzeugen virtuelle RDF-Graphs über bestehende SQL-Datenbanken → du kannst mit SPARQL abfragen, während die Daten physisch in MySQL / PostgreSQL liegen.
• Umgekehrt (RDF-Store aber SQL-Syntax) gibt es z. B. Virtuoso oder Stardog, die sowohl SPARQL als auch einen SQL-Dialekt anbieten – allerdings proprietär.
• Ein direkter „Prisma-Adapter für SPARQL“ existiert bislang nicht.
Tip: Symbol('…') avoids key collisions with other decorators.
────────────────────────────────────────
3 | Leverage TypeScript’s emitDecoratorMetadata
────────────────────────────────────────
If "emitDecoratorMetadata": true is enabled, TypeScript will automatically store some extra metadata for you:
• design:type → property type
• design:paramtypes → constructor / method parameter types
• design:returntype → method return type
Example:
ts
import 'reflect-metadata';
function LogType(): PropertyDecorator {
return (target, key) => {
const t = Reflect.getMetadata('design:type', target, key);
console.log(`${String(key)} is a ${t.name}`);
};
}
class Foo {
@LogType()
age!: number; // ⇒ logs: "age is a Number"
@LogType()
title!: string; // ⇒ logs: "title is a String"
// For params:
method(@LogType() _x: Date) {} // logs at decorator-time
}
Limitations
• Only primitive constructor functions (String, Number, Boolean, Array, Object) or user-defined classes are emitted. Unions, intersections, mapped types, etc., are not preserved.
• Works only when you actually run the compiled JS (obvious but often forgotten in tests).
────────────────────────────────────────
4 | Prototype vs. constructor cheat-sheet
────────────────────────────────────────
• Property decorator on instance property → target is prototype
• Property decorator on static property → target is constructor
• Class decorator → target is constructor
• Method decorator (instance) → target is prototype
• Parameter decorator: add’l arg parameterIndex identifies which one.