Skip to content

Literals as types  #1195

@aspnetde

Description

@aspnetde

I propose we implement something like what's known as Literal Types in TypeScript:

const foo = (bar: "A" | "B") => {}

foo("A"); // ok
foo("C"); // forbidden

However, as in TypeScript, it should not be limited to literals. In fact, TS accepts any type here:

interface Options {
  width: number;
}
function configure(x: Options | "auto") {}
configure({ width: 100 }); // ok
configure("auto"); // ok
configure("automatic"); // forbidden

As someone who is actively working on an application for the last couple of months which uses TS for the frontend and F# for the backend, I find myself often missing this capability when switching from TS to F#. Right now, I have to explicitly define a discriminated union to do that in F#:

type Bar = A | B
let foo (bar: Bar) = ()
foo A

Instead, it would be really neat to define that DU "on the fly" or "inline" (not sure what the proper wording might be) as in TypeScript:

let foo (bar: A | B) = ()

Pros and Cons

Advantages: More flexibility, I guess.

Disadvantages: As always, it's not a silver bullet. There are plenty of reasons one may want to define the type of that parameter explicitly, e.g., to reuse it elsewhere.

Affidavit

Please tick this by placing a cross in the box:

  • This is not a question (e.g. like one you might ask on stackoverflow) and I have searched stackoverflow for discussions of this issue
  • I have searched both open and closed suggestions on this site and believe this is not a duplicate
  • This is not something which has obviously "already been decided" in previous versions of F#. If you're questioning a fundamental design decision that has obviously already been taken (e.g. "Make F# untyped") then please don't submit it.

Please tick all that apply:

  • This is not a breaking change to the F# language design
  • I or my company would be willing to help implement and/or test this

For Readers

If you would like to see this issue implemented, please click the 👍 emoji on this issue. These counts are used to generally order the suggestions by engagement.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions