skunkteam / types Goto Github PK
View Code? Open in Web Editor NEWRuntime type-validation with auto-derived TypeScript types
Runtime type-validation with auto-derived TypeScript types
Similar to the existing properties minLength
and minLength
add support for properties uniqueItems
and sorted
.
uniqueItems
boolean true
(or perhaps an optional selector function to only enforce uniqueness of a specific value)?With this feature we would no longer need to define custom types like:
/**
* An array with length > 0 and distinct values.
* Allows custom comparator function to specify 'distinct' values, defaults to 'isEqual', which performs a deep comparison between two values for equality comparison.
* Note that although array length is validated, the array element(s) itself may still be falsy (undefined etc.) depending on the elementType.
* WARNING: Be sure to document the distinct behavior in de OpenApiMetadata of the type you are using this with so API consumers are aware
* of this restriction
* @param elementType the type of the array elements.
*/
type NonEmptyDistinctArray<T> = Branded<T[], 'NonEmptyDistinctArray'>;
function NonEmptyDistinctArray<T>(elementType: Type<T>, comparatorFn: Comparator<T> = isEqual): Type<NonEmptyDistinctArray<T>> {
const type = NonEmptyArray<T>(elementType)
// Set the brand to plain `NonEmptyDistinctArray`:
.withConstraint('NonEmptyDistinctArray', value => {
return uniqWith(value, comparatorFn).length === value.length || 'no duplicate values allowed';
});
// But set the runtime name to be more specific:
Object.defineProperty(type, 'name', { value: `NonEmptyDistinctArray<${elementType.name}>` });
return type;
}
type NonEmptyDistinctSortedDates<T> = Branded<T[], 'NonEmptyDistinctSortedDates' | 'NonEmptyDistinctArray'>;
function NonEmptyDistinctSortedDates<T extends ISODate>(elementType: Type<T>) {
const type = NonEmptyDistinctArray<T>(elementType)
// Set the brand to plain `NonEmptyDistinctSortedDates`:
.withConstraint('NonEmptyDistinctSortedDates', value => {
return value.every(pairwise((next, prev) => !prev || next > prev)) || 'should be sorted by date';
});
// But set the runtime name to be more specific:
Object.defineProperty(type, 'name', { value: `SortedByDate<${elementType.name}>` });
return type;
}
with:
/**
* An array with length > 0.
* Note that although array length is validated, the array element(s) itself may still be falsy (undefined etc.) depending on the elementType.
* @param elementType the type of the array elements.
*/
export function NonEmptyArray<T>(elementType: Type<T>): Type<T[]> {
return array(elementType).withConfig(`NonEmptyArray<${elementType.name}>`, {
minLength: 1,
customMessage: `expected at least one ${elementType.name}`,
});
}
As shown in the list of autoCast parsers, string.autoCast
currently accepts absolutely anything:
Input | Output |
---|---|
false |
"false" |
123 |
"123" |
null |
"null" |
undefined |
"undefined" |
Symbol.iterator |
"Symbol(Symbol.iterator)" |
{ prop: "value" } |
"[object Object]" |
() => { /* really? */ } |
"() => { /* really? */ }" |
The idea at the time was: Because the String
type-constructor is able to convert anything to string
, so should the string.autoCast
type. This turns out to be not so great in practice.
Take the following example:
/** This type defines the input that the user can enter using an HTML form. */
type MyFormInput = The<typeof MyFormInput>;
const MyFormInput = object("MyFormInput", {
requiredString: string,
requiredNumber: number,
}).autoCastAll; // <- note the `autoCastAll` here
Often, this kind of type is used in autoCastAll
mode to make sure that all kinds of input from HTML form elements are converted into the right types before use in our logic or before converting to JSON. For example, it is often the case that numeric input needs to be parsed from a string
.
That works of course:
MyFormInput({ requiredString: "user input", requiredNumber: "42" }); // { requiredString: "user input", requiredNumber: 42 }
But what happens if the user never touched the UI field that fills requiredString
?
MyFormInput({ requiredString: undefined, requiredNumber: "42" }); // { requiredString: "undefined", requiredNumber: 42 }
Well, that is awkward. By design, undefined
(like any other value) is accepted by string.autoCast
, but that is hardly ever our intention. In this case requiredString
was explicitly modeled to be required. It should not accept undefined
.
My suggestion would be to only accept bigint
, boolean
, number
and string
and fail on any other type:
That would result in the following table:
Input | Output |
---|---|
false |
"false" |
123 |
"123" |
123n |
"123" |
"abc" |
"abc" |
null |
error in parser of [string.autoCast]: could not autocast value: null |
undefined |
error in parser of [string.autoCast]: could not autocast value: undefined |
Symbol.iterator |
error in parser of [string.autoCast]: could not autocast value: [Symbol: Symbol.iterator] |
{ prop: "value" } |
error in parser of [string.autoCast]: could not autocast value: { prop: "value" } |
function myFunc() {} |
error in parser of [string.autoCast]: could not autocast value: [Function: myFunc] |
This is of course a breaking change.
main
branch failed. π¨I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.
You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. Iβm sure you can fix this πͺ.
Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.
Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the main
branch. You can also manually restart the failed CI job that runs semantic-release.
If you are not sure how to resolve this, here are some links that can help you:
If those donβt help, or if this issue is reporting something you think isnβt right, you can always ask the humans behind semantic-release.
The npm token configured in the NPM_TOKEN
environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/
.
If you are using Two Factor Authentication for your account, set its level to "Authorization only" in your account settings. semantic-release cannot publish with the default "
Authorization and writes" level.
Please make sure to set the NPM_TOKEN
environment variable in your CI with the exact value of the npm token.
Good luck with your project β¨
Your semantic-release bot π¦π
When putting a .literal() inside a type, .literal(string) input is not accepted:
For example this is not accepted:
/** a secret bundle type */
export type SecretBundle = The<typeof SecretBundle>;
export const SecretBundle = object('SecretBundle', {
api_key: NonEmptyString,
password: NonEmptyString,
user: NonEmptyString,
});
/** how we want to use the secret bundle */
export type SpecificMyappSecretBundle = The<typeof SpecificMyappSecretBundle>;
export const SpecificMyappSecretBundle = object('SpecificMyappSecretBundle', {
MYAPP_API_USER: literal('MYTEAM'),
MYAPP_API_PASSWORD: NonEmptyString,
MYAPP_API_KEY: NonEmptyString,
});
const secrets = SecretBundle(JSON.parse(SecretString));
const parsedSecrets = SpecificMyappSecretBundle.literal({
MYAPP_API_USER: secrets.user,
MYAPP_API_PASSWORD: secrets.password,
MYAPP_API_KEY: secrets.api_key,
});
And this is:
/** a secret bundle type */
export type SecretBundle = The<typeof SecretBundle>;
export const SecretBundle = object('SecretBundle', {
api_key: NonEmptyString,
password: NonEmptyString,
user: NonEmptyString,
});
type MYTEAM = The<typeof MYTEAM>;
const MYTEAM = literal('MYTEAM');
/** how we want to use the secret bundle */
export type SpecificMyappSecretBundle = The<typeof SpecificMyappSecretBundle>;
export const SpecificMyappSecretBundle = object('SpecificMyappSecretBundle', {
MYAPP_API_USER: MYTEAM,
MYAPP_API_PASSWORD: NonEmptyString,
MYAPP_API_KEY: NonEmptyString,
});
const secrets = SecretBundle(JSON.parse(SecretString));
const parsedSecrets = SpecificMyappSecretBundle.literal({
MYAPP_API_USER: MYTEAM(secrets.user),
MYAPP_API_PASSWORD: secrets.password,
MYAPP_API_KEY: secrets.api_key,
});
I am trying to build a generic type with @skunkteam/types
that takes an existing (object) type and extends it with a number of fields (id
in this example):
import { BaseObjectLikeTypeImpl, intersection, object, string, The, TypeImpl } from '@skunkteam/types';
export type ObjectType<ResultType> = TypeImpl<BaseObjectLikeTypeImpl<ResultType>>;
export type Person = The<typeof Person>;
export const Person = object('Person', { name: string });
export type RestDocument<T> = T & { id: string };
export function RestDocument<T>(type: ObjectType<T>): ObjectType<RestDocument<T>> {
return intersection(`RestDocument<${type.name}>`, [object({ id: string }), type]);
}
Unfortunately this throws a typescript error:
error TS2322: Type 'TypeImpl<IntersectionType<[TypeImpl<InterfaceType<{ id: TypeImpl<BaseTypeImpl<string>>; }, TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>>>, TypeImpl<...>]>>' is not assignable to type 'TypeImpl<BaseObjectLikeTypeImpl<RestDocument<T>>>'.
Type 'TypeImpl<IntersectionType<[TypeImpl<InterfaceType<{ id: TypeImpl<BaseTypeImpl<string>>; }, TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>>>, TypeImpl<...>]>>' is not assignable to type 'BaseObjectLikeTypeImpl<RestDocument<T>>'.
The types returned by 'and(...)' are incompatible between these types.
Type 'TypeImpl<IntersectionType<[TypeImpl<IntersectionType<[TypeImpl<InterfaceType<{ id: TypeImpl<BaseTypeImpl<string>>; }, TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>>>, TypeImpl<...>]>>, any]>>' is not assignable to type 'TypeImpl<IntersectionType<[BaseObjectLikeTypeImpl<RestDocument<T>>, any]>>'.
Type 'TypeImpl<IntersectionType<[TypeImpl<IntersectionType<[TypeImpl<InterfaceType<{ id: TypeImpl<BaseTypeImpl<string>>; }, TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>>>, TypeImpl<...>]>>, any]>>' is not assignable to type 'IntersectionType<[BaseObjectLikeTypeImpl<RestDocument<T>>, any]>'.
Types of property 'types' are incompatible.
Type '[TypeImpl<IntersectionType<[TypeImpl<InterfaceType<{ id: TypeImpl<BaseTypeImpl<string>>; }, TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>>>, TypeImpl<...>]>>, any]' is not assignable to type '[BaseObjectLikeTypeImpl<RestDocument<T>>, any]'.
Type 'TypeImpl<IntersectionType<[TypeImpl<InterfaceType<{ id: TypeImpl<BaseTypeImpl<string>>; }, TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>>>, TypeImpl<...>]>>' is not assignable to type 'BaseObjectLikeTypeImpl<RestDocument<T>>'.
The types returned by 'and(...)' are incompatible between these types.
Type 'TypeImpl<IntersectionType<[TypeImpl<IntersectionType<[TypeImpl<InterfaceType<{ id: TypeImpl<BaseTypeImpl<string>>; }, TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>>>, TypeImpl<...>]>>, any]>>' is not assignable to type 'TypeImpl<IntersectionType<[BaseObjectLikeTypeImpl<RestDocument<T>>, any]>>'.
Type 'TypeImpl<IntersectionType<[TypeImpl<IntersectionType<[TypeImpl<InterfaceType<{ id: TypeImpl<BaseTypeImpl<string>>; }, TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>>>, TypeImpl<...>]>>, any]>>' is not assignable to type 'IntersectionType<[BaseObjectLikeTypeImpl<RestDocument<T>>, any]>'.
Types of property 'types' are incompatible.
Type '[TypeImpl<IntersectionType<[TypeImpl<InterfaceType<{ id: TypeImpl<BaseTypeImpl<string>>; }, TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>>>, TypeImpl<...>]>>, any]' is not assignable to type '[BaseObjectLikeTypeImpl<RestDocument<T>>, any]'.
Type 'TypeImpl<IntersectionType<[TypeImpl<InterfaceType<{ id: TypeImpl<BaseTypeImpl<string>>; }, TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>>>, TypeImpl<...>]>>' is not assignable to type 'BaseObjectLikeTypeImpl<RestDocument<T>>'.
The types returned by 'typeValidator(...)' are incompatible between these types.
Type 'Result<MergeIntersection<T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>>>' is not assignable to type 'Result<RestDocument<T>>'.
Type 'Success<MergeIntersection<T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>>>' is not assignable to type 'Result<RestDocument<T>>'.
Type 'Success<MergeIntersection<T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>>>' is not assignable to type 'Success<RestDocument<T>>'.
Type 'MergeIntersection<T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>>' is not assignable to type 'RestDocument<T>'.
Type '(T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>) | { [P in keyof (T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>)]: MergeIntersection<...>; }' is not assignable to type 'RestDocument<T>'.
Type '{ [P in keyof (T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>)]: MergeIntersection<(T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>)[P]>; }' is not assignable to type 'RestDocument<T>'.
Type '{ [P in keyof (T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>)]: MergeIntersection<(T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>)[P]>; }' is not assignable to type 'T'.
'T' could be instantiated with an arbitrary type which could be unrelated to '{ [P in keyof (T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>)]: MergeIntersection<(T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>)[P]>; }'.
Type 'MergeIntersection<(T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>)[P]>' is not assignable to type 'T[P]'.
Type '{ id: string; }' is not assignable to type 'RestDocument<T>'.
Type '{ id: string; }' is not assignable to type 'T'.
'T' could be instantiated with an arbitrary type which could be unrelated to '{ id: string; }'.
Type 'MergeIntersection<T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>>' is not assignable to type 'T'.
'T' could be instantiated with an arbitrary type which could be unrelated to 'MergeIntersection<T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>>'.
Type '(T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>) | { [P in keyof (T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>)]: MergeIntersection<...>; }' is not assignable to type 'T'.
'T' could be instantiated with an arbitrary type which could be unrelated to '(T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>) | { [P in keyof (T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>)]: MergeIntersection<...>; }'.
Type '{ [P in keyof (T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>)]: MergeIntersection<(T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>)[P]>; }' is not assignable to type 'T'.
'T' could be instantiated with an arbitrary type which could be unrelated to '{ [P in keyof (T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>)]: MergeIntersection<(T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>)[P]>; }'.
Type 'MergeIntersection<(T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>)[P]>' is not assignable to type 'T[P]'.
Type '(T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>)[P] | { [P in keyof (T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>)[P]]: MergeIntersection<...>; }' is not assignable to type 'T[P]'.
Type '{ [P in keyof (T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>)[P]]: MergeIntersection<(T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>)[P][P]>; }' is not assignable to type 'T[P]'.
Type 'MergeIntersection<(T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>)["id" | keyof T]>' is not assignable to type 'T[P]'.
Type '(T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>)["id" | keyof T] | { [P in keyof (T & TypeOfProperties<Writable<{ id: TypeImpl<...>; }>>)["id" | keyof T]]: MergeIntersection<...>; }' is not assignable to type 'T[P]'.
Type '(T["id"] & string) | (T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>)[keyof T]' is not assignable to type 'T[P]'.
Type 'T["id"] & string' is not assignable to type 'T[P]'.
Type 'MergeIntersection<T["id"] & string> | MergeIntersection<(T & TypeOfProperties<Writable<{ id: TypeImpl<BaseTypeImpl<string>>; }>>)[keyof T]>' is not assignable to type 'T[P]'.
Type 'MergeIntersection<T["id"] & string>' is not assignable to type 'T[P]'.
Type '(T["id"] & string) | { [P in keyof (Record<string | number | symbol, unknown> & T["id"] & string)]: MergeIntersection<(Record<string | number | symbol, unknown> & T["id"] & string)[P]>; }' is not assignable to type 'T[P]'.
Type 'T["id"] & string' is not assignable to type 'T[P]'.
Type 'string' is not assignable to type 'T[P]'.
Type '{ id: string; }' is not assignable to type 'T'.
'T' could be instantiated with an arbitrary type which could be unrelated to '{ id: string; }'.
... or find a way to exist together?
When constructing a union type using the union(name, [types])
signature, all brandings of types
are preserved. This is not the case when constructing a union type using the .or(otherType)
'constructor', which strips the branding of otherType
.
Because of this, .or()
creates unexpectedly lenient types:
const BrandedA = literal('A').withBrand('BrandA');
const BrandedB = literal('B').withBrand('BrandB');
type BrandedUnion = The<typeof BrandedUnion>;
const BrandedUnion = union('BrandedUnion', [BrandedA, BrandedB]);
// Good: WithBrands<"A", "BrandA"> | WithBrands<"B", "BrandB">
type BrandedOr1 = The<typeof BrandedOr1>;
const BrandedOr1 = BrandedA.or(BrandedB);
// Bad: WithBrands<"A", "BrandA"> | "B"
type BrandedOr2 = The<typeof BrandedOr2>;
const BrandedOr2 = BrandedB.or(BrandedA);
// Bad: WithBrands<"B", "BrandB"> | "A"
The suggested nestjs pipe from the README doesn't work with a unknownRecord
type:
@Injectable()
export class TypeValidationPipe implements PipeTransform {
transform(value: unknown, { metatype }: ArgumentMetadata) {
if (!isType(metatype)) {
// You may want to warn or error, instead of skipping
// validation, that is up to you.
return value;
}
const result = metatype.validate(value, { mode: 'construct' });
if (result.ok) {
return result.value;
}
throw new BadRequestException(reportError(result));
}
}
Using this in a nestjs controller throws a typescript error:
@Post('foo')
foo(@Body() doc: unknownRecord) {
console.log(doc);
}
error TS2749: 'unknownRecord' refers to a value, but is being used as a type here. Did you mean 'typeof unknownRecord'?
But declaring a local type with typeof unknownRecord
doesn't seem to fix the issue. There is a workaround with a local "copy" of unknownRecord and a local type definition:
type AnyRecord = The<typeof AnyRecord>;
const AnyRecord = unknownRecord;
With this workaround, you can use AnyRecord
as a parameter type to a controller method. Is it possible for skunkteam/types to also export The<typeof unknownRecord>
(and perhaps other unknown variants as well)?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.