fslang-suggestions icon indicating copy to clipboard operation
fslang-suggestions copied to clipboard

Literals as types

Open aspnetde opened this issue 2 years ago • 21 comments

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:

  • [x] This is not a question (e.g. like one you might ask on stackoverflow) and I have searched stackoverflow for discussions of this issue
  • [x] I have searched both open and closed suggestions on this site and believe this is not a duplicate
  • [x] 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:

  • [x] This is not a breaking change to the F# language design
  • [x] 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 :+1: emoji on this issue. These counts are used to generally order the suggestions by engagement.

aspnetde avatar Oct 21 '22 06:10 aspnetde