Skip to content

Constrain object literal without losing the keys and values #3708

Closed
@Ciantic

Description

@Ciantic

Simple example:

var out: {[name: string] : number} = { a: 5, b: 10 };
out.a // Is not valid

It would be nice if we could retain the keys and values, but still constrain the object literal. For backwards compatibility it probably can't be introduced in above syntax, but perhaps new syntax is required like var out: Object<string, number> or something.

Here is a longer use case, where it is important to retain the keys and values:

interface Field<T> {
    clean(input: T): T
}

class CharField implements Field<string> {
    clean(input: string) {
        return "Yup";
    }
}

class NumberField implements Field<number> {
    clean(input: number) {
        return 123;
    }
}

class ObjectField<A, T extends { [name: string]: Field<any> }> implements Field<A> {
    fields : T
    constructor(fields : T) {
        this.fields = fields;
    }

    clean(input: A) {
        return <A>{}
    }
}

var person = new ObjectField({
    id: new NumberField(),
    name: new CharField()
});

person.fields.id // Is not valid at the moment

It does work if I remove the constrain, and modify it to this:

class ObjectField<A, T> implements Field<A> {
    fields : T
    constructor(fields : T) {
        this.fields = fields;
    }

    clean(input: A) {
        return <A>{}
    }
}


person.fields.id // Is valid and checks as NumberField!

But now I loose the constraint on the T, which in this case should say that right hand side of T is Field.

As a bonus, If one looks at the ObjectField really hard, it is difficult to use it without this: #3448 implemented also.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Breaking ChangeWould introduce errors in existing codeCommittedThe team has roadmapped this issueFixedA PR has been merged for this issueSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions