Skip to content

Specifying object literal types on the fly #11216

Closed
@normalser

Description

@normalser

Sometimes it would be handful to be able to specify type of object literal on the fly (without creating const / variable) with exact type definition

Hopefully it's not violating 'no new syntax' rule (too much)

So something like that:

interface A {
    a: string
}

const b = {
    c: {
        a: 'test'
    }:A   // b would be of type { c: A }
}


function test(d:string) {
    switch(d) {
        case 'anotherTest': return {a: 'test'}:A  // function would return type A
    }
}

Right now the closest I can get is to use type assertion

const b = {
    c: {
        a: 'test'
    } as A
}

but it will allow to provide more fields than necessary and I would want TS to throw an error if someone provides more fields

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions