Giter VIP home page Giter VIP logo

types's People

Contributors

dependabot[bot] avatar njirem avatar pavadeli avatar tond83 avatar untio11 avatar wvanderdeijl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Forkers

richardolrichs

types's Issues

feature request - add `uniqueItems ` and `sorted` properties to array type

Similar to the existing properties minLength and minLength add support for properties uniqueItems and sorted.

  • Sorted should accept a selector function to specify the value to sort on (perhaps also sort order).
  • 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}`,
    });
}

Change `string.autoCast` behaviour on anything other than boolean and number

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.

The automated release is failing 🚨

🚨 The automated release from the 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.


Invalid npm token.

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 πŸ“¦πŸš€

.literal(string) input on a type with .literal() inside the type issue

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,
});

Type of intersection of two object types A and B is not equal to A & B

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; }'.

Union type constructor `.or(other)` strips branding of `other`

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"

unknownRecord cannot be used in nestjs pipe

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)?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.