Skip to content

as expression and array of union types #28251

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
agentcooper opened this issue Oct 31, 2018 · 3 comments
Closed

as expression and array of union types #28251

agentcooper opened this issue Oct 31, 2018 · 3 comments
Labels
Question An issue which isn't directly actionable in code

Comments

@agentcooper
Copy link
Contributor

I'm not 100% sure this is a bug, but the behavior is not clear to me.

As a part of the state object I have an array that I want to be inferred as an array of the union type. I know this can be done by providing a type for the whole state (const state: State = ...), but I would like to rely on type inference since there are many other state properties of primitive types.

type Fruit = "banana" | "apple";

// option 1

const state1 = {
    // OK: works as expected
    fruits: (["banana", "apple"] as Array<Fruit>),
    expression: 1 + 2
};

// option 2

const state2_1 = {
    // OK: error is expected
    fruits: [1, 2, 3] as Array<Fruit>,
    expression: 1 + 2
}

const state2_2 = {
    // NOT OK: error is expected, but not shown!
    fruits: ["banana", "apple", "potato"] as Array<Fruit>,
    expression: 1 + 2
}

// option 3

function inferAsUnionArray<K, T extends K = K>(input: Array<T>) {
    const out: Array<K> = input;
    return out;
}

const state3 = {
    // OK: error as expected. can this be done easier?
    fruits: inferAsUnionArray<Fruit>(["banana", "apple", "potato"]),
    expression: 1 + 2
};

Playground link.

@AnyhowStep
Copy link
Contributor

There is no "static assert" in the C++ sense in TS. Although I wish there was...

I use a similar "hack" as your state3, sometimes

@weswigham
Copy link
Member

Casts allow any types that possibly overlap to be converted. What you want is indeed a kind of type assertion expression. The function call is currently the best safe way to do it, IMO. We have an open issue tracking related suggestions: #26064 I'd chime in there.

@weswigham weswigham added the Question An issue which isn't directly actionable in code label Oct 31, 2018
@typescript-bot
Copy link
Collaborator

This issue has been marked as 'Question' and has seen no recent activity. It has been automatically closed for house-keeping purposes. If you're still waiting on a response, questions are usually better suited to stackoverflow.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

4 participants