Type Safety
Since v6.6.0, a Repository<T> checks its query options against the entity class T at compile
time. The field names in sort, projection and plain-object filters come from the entity, your
editor suggests them, and a misspelled name fails to compile. The result type of a find*,
create() or update() call also follows the projection: a field you did not ask for is not on
the result type.
You get this from any repository created from an entity class, because getRepository() infers
T from it:
const repo = client.getRepository(Customer); // Repository<Customer>
The examples on this page use these two entities:
import { BaseEntity, Column, DataType, Embedded, Entity, Link, PrimaryKey } from '@sqb/connect';
class Address {
@Column()
declare city?: string;
@Column()
declare street?: string;
}
@Entity('countries')
export class Country extends BaseEntity {
@PrimaryKey()
@Column()
declare code: string;
@Column()
declare name: string;
}
@Entity('customers')
export class Customer extends BaseEntity {
@PrimaryKey()
@Column()
declare id: number;
@Column({ fieldName: 'given_name' })
declare givenName: string;
@Column({ fieldName: 'family_name' })
declare familyName: string;
@Column({ fieldName: 'country_code' })
declare countryCode: string;
@Column({ fieldName: 'birth_date', dataType: DataType.DATE, exclusive: true })
declare birthDate?: Date;
@Column()
declare active: boolean;
@Embedded(Address, { fieldNamePrefix: 'address_' })
declare address: Address;
@(Link({ exclusive: true }).toOne(() => Country, { sourceKey: 'countryCode', targetKey: 'code' }))
declare readonly country?: Country;
}
Field paths
The type EntityPath<T> lists the field paths of an entity. A path is:
- a property name of the class:
'givenName'. It is the property name, not the databasefieldName, so'given_name'is not a path; - a dotted path into an
@Embeddedobject or the target of a@Link:'address.city','country.name'. A to-many link continues into its element type.
Methods are not paths, and a column value (a string, a number, a Date) ends a path. Paths stop
after 4 segments, because links can point back at each other (Customer → Country →
customers → ...).
sort
Each sort item is a field path, optionally prefixed with + (ascending, the default) or -
(descending):
await repo.findMany({ sort: ['-givenName', 'country.name'] });
projection
Each projection item is a field path with an optional + or - prefix. A dotted path can
carry a sign on its last segment too, as in 'country.-code'. The comma and bracket forms
described under Repositories → Projection are accepted as well:
await repo.findMany({ projection: ['givenName', 'country.-code'] });
await repo.findMany({ projection: 'country(code,name)' });
The result type follows the projection
When the projection is a literal made of known paths, the result type keeps only the fields the query returns. The rules are the same ones the query uses at runtime, applied level by level:
- If a level names a field without a sign, only the named fields come back.
- If a level names fields only with
+or-, the default fields come back,+fields are added and-fields are left out. - A dotted path applies the same rules one level down, inside the object or link target its first segment names.
All fields stay optional, as in PartialDTO<T>.
const a = await repo.findMany({ projection: ['givenName', 'country.name'] });
// { givenName?: string; country?: { name?: string } }[]
const b = await repo.findOne({ projection: '-familyName' });
// every field of Customer except familyName
const c = await repo.findById(1, { projection: ['+country.name'] });
// the default fields of Customer, plus country with only its name
Reading a field that the projection leaves out is a compile error:
const rows = await repo.findMany({ projection: ['givenName'] });
rows[0].familyName; // error: Property 'familyName' does not exist
Two cases fall back to wider types:
- A projection that is not a literal of known paths (a
stringvalue from a request, or the comma and bracket forms) returnsPartialDTO<T>. - No projection at all returns
T.
The type cannot see which fields are exclusive.
When a level keeps the default fields, the result type still lists exclusive fields such as
birthDate, although the query does not return them unless you ask for them with +.
Filters
A plain-object filter on a typed repository is checked key by key:
- Each key is a column path, optionally followed by an operator:
'id >=','country.name like'. The space before the operator is optional for>=,<=,!=,>,<and=('id>='). A key without an operator meanseq, orinfor an array value. A link or embedded object on its own ('country','address') is not a column path; name one of its columns ('country.code'). - Each value must fit the column type. A number column takes a number (or
bigint), aDatecolumn takes aDateor a string. Every column also takes an array (forinandbetween),null, or an@sqb/builderelement such asParam('name')orField('other'). - Filters nested in
andandorare checked the same way.
import { Param } from '@sqb/builder';
await repo.findMany({
filter: {
'id >=': 5,
'birthDate <': new Date(),
'country.name like': 'T%',
countryCode: Param('code'),
or: [{ active: true }, { 'address.city': null }],
},
params: { code: 'TR' },
});
await repo.findMany({ filter: { id: 'x' } }); // error: a string for a number column
@sqb/builder operators (Eq('id', 1), And(...)) are not checked: their field names are plain
strings.
Misspelled fields
A literal field name that does not exist on the entity fails to compile. The error message names the field:
await repo.findMany({ sort: ['givenNmae'] });
// Type '"givenNmae"' is not assignable to type '"givenNmae" & { readonly 'Unknown field': "givenNmae"; }'
await repo.count({ filter: { cuntry: 'TR' } });
// Type '"TR"' is not assignable to type '"Unknown filter field: cuntry"'
Some values cannot be checked at compile time. These compile, and the repository checks them when the query runs:
- values typed
string, such as a sort field read from an HTTP query; - computed filter keys (
{ [key]: value }); - options stored in a variable typed
Repository.FindManyOptions<Customer>before the call; - every call on a
Repository<any>.
Upgrading to 6.6.0
Code that compiled with earlier versions can fail to compile after the upgrade:
- Field names are case-sensitive in the types. The runtime matches field names in any case,
but the types do not, so
sort: ['GivenName']no longer compiles. Write'givenName'. - Reading a field outside the projection is a type error. The result type of a call with a projection keeps only the projected fields. Add the field to the projection, or drop the projection if you need the whole entity.
- A filter typed
objector as aninterfaceis rejected. A typed repository does not take afilterwhose type isobjector an interface type, because their keys cannot be checked. Declare the variable asEntityFilter<Customer>(exported from@sqb/connect), use atypealias instead of an interface, or spread it into an object literal (filter: { ...criteria }). - Mixing
+fieldwith an unsignedfield.subnarrows too far. With['+country', 'country.name']the query keeps the default fields, because the+applies tocountry, but the type reads the unsigned'country.name'as "onlycountry". Write'+country.name'instead: both the query and the type then keep the default fields pluscountry.name.