Skip to content
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

Will C# ever implement these type annotation features from typescript? #11848

Closed
Liero opened this issue Jun 8, 2016 · 14 comments
Closed

Will C# ever implement these type annotation features from typescript? #11848

Liero opened this issue Jun 8, 2016 · 14 comments

Comments

@Liero
Copy link

Liero commented Jun 8, 2016

I'm just curious, whether some of TypeScript's type annotation features were already considered as candidates for C#.

One may consider them to be nice typescript features another as necessary evil in order to bring some type safety to javascript.

What do you think about these?

1. interfaces ala TypeScript:

TypeScript example

interface IPerson { firstName: string; lastName: string; }
function foo(person: IPerson) {..}

//we can call Foo with any object that has properties defined by IPerson:
foo({firstName: "Lorem", lastName: "Ipsum"});
foo(new Person("Lorem", "Ipsum"));

C# example

this could be useful especially in combination with anonymous types:

Foo(new { FirstName = "Lorem", LastName="Ipsum" });

db.Customers.Select(Foo);

var person = db.Customers.Select(p => new { p.Id, p.FirstName, p.LastName }).First();
Foo(person);

IPerson person = new { FirstName = "Lorem", LastName="Ipsum" };

it could also help with intellisense when writing anonymous types:
IPerson person = new { F... - autocompletion list
foo(new { FirstName="Lorem", ... - autocompletion list

2. Intersection types

TypeScript example

interface IEntity { id: number; }
function foo(person: IPerson & IEntity) {
  console.log(`${person.id}\t${person.firstName} ${person.lastName}`);
}

C# example

void Foo(IPerson & IEntity person) {
  Console.WriteLine($"{person.Id}\t{person.FirstName} {person.LastName}");
}

3. Union types

TypeScript example

function format(value: number | Date) {...}
format(12345);
format(new Date());

C# example

type Formatable = int | double | decimal | DateTime 
string Format(Formatable value) {...} 
Format(12345);
Format(DateTime.Now);

4. String Literals (and other literals)

TypeScript example

function animate(speed: "slow" | "fast");

C# example

enum Speed { Slow, Fast, VeryFast }
type AnimatableSpeed = Speed.Slow | Speed.Fast;
void Animate(AnimatableSpeed  speed);
Animate(Speed.Slow);
Animate(Speed.VeryFast); // compiler error

string literals could be usefull to annotate proxy classes defined by 3rd party. For example, when REST service returns string values like "OK", "NOT OK", then enums cannot be effectively used.

5. Anonymous Interfaces

TypeScript example

let entities = new Array<{ id: number}>();

C# example

var entities = new List<{ int Id; }> {
   new { Id = 1 },
   new { Id = 2, FirstName = "Lorem", LastName = "Ipsum" }
};

class MyList<T> : List<T> where T : { int Id; }
@HaloFour
Copy link

HaloFour commented Jun 8, 2016

  1. There was a proposal for something like this, Feature request: Anonymous types that implement interfaces #13. However, it was been declined.
  2. This would require CLR support. The closest you can get to it now is with generic type constraints.
  3. This would also require CLR support, and I'm not certain how useful it would really be given that any IL emitted by a single method needs to be tailored to the type accepted. It's not like JavaScript where accessors/methods are dynamically dispatched, the declaring type of the member needs to be embedded at the call site.
  4. Why not just use an enum? That's what TypeScript is attempting to emulate anyway.
  5. I'm not sure how useful this would be. An interface represents a contract. A throwaway contract doesn't seem like it has much purpose since it couldn't be referenced outside of where it was declared. To any consumer, that interface wouldn't exist.

@gafter
Copy link
Member

gafter commented Jun 8, 2016

The short answer is "yes".

@Liero Liero changed the title Will typescript event implement these type annotation features? Will C# event implement these type annotation features from typescript? Jun 9, 2016
@Liero Liero changed the title Will C# event implement these type annotation features from typescript? Will C# ever implement these type annotation features from typescript? Jun 9, 2016
@Liero
Copy link
Author

Liero commented Jun 9, 2016

@HaloFour:

#.1 I don't see why "Intersection Types" would require change to CLR. It is possible now with dynamic keyword - of course without type safety and probably with performance costs. But typesafety can be checked by compiler. Second, if #.1 was added to C#, then "Intersection Types" could be implemented as compiled generated "interface ala typescript"

#.5 It only makes sense with interfaces from #.1. We should really give them another name...

@Liero
Copy link
Author

Liero commented Jun 9, 2016

#.4 I see two usages.
First, to restict possible values of an enum, see the updated C# example.
Second, to define possible output values, where enum cannot be used. For example, when you have autogenerated REST API proxy. If the API can by definition return either "OK" or "NOT OK", then I believe string literals would be usefull.

@HaloFour
Copy link

HaloFour commented Jun 9, 2016

@Liero

dynamic incurs severe performance penalties. I seriously doubt that the compiler team would consider that a suitable implementation. Not to mention, dynamic already exists, so if you wanted that you could already use it.

Interfaces are a very different beast in the CLR from what they are in TypeScript. Even if the compiler could just generate a new composite interface extending the intersection interfaces, no type would actually satisfy that generated interface. It's not sufficient to have the same members, implementing types must actually declare that they implement the interface and fill in the required v-table slots.

public interface IFoo {
    void Foo();
}

public interface IBar {
    void Bar();
}

public class FooBar : IFoo, IBar {
    public void Foo() { }
    public void Bar() { }
}

public interface IFooBar : IFoo, IBar { }

var foobar = new FooBar();
IFooBar duck = foobar; // compiler error

@Liero
Copy link
Author

Liero commented Jun 9, 2016

public interface IFoo {
    void Foo();
    void Hello();
}

public interface IBar {
    void Bar();
    void Hello();
}

public class FooBar : IFoo, IBar {
    public void Foo() { }
    public void Bar() { }
    public void Hello() { }
}

var foobar = new FooBar();

interface IFooBarUnion = IFoo & IBar;
IFooBarUnion duck = foobar;   //*   object duck = FooBar();
duck.Foo();                   //*   ((IFoo)duck).Foo();
duck.Bar();                   //*   ((IBar)duck).Bar();
duck.Hello();                 //*   ((IFoo)duck).Hello(); ?? could be problem if IFoo.Hello had implementation different from IBar.Hello

interface IFooBarIntersection = IFoo | IBar;
IFooBarIntersection duck2 = foobar;
duck2.Hello(); //*  ((IFoo)duck).Hello(); ?? could be problem if IFoo.Hello had implementation different from IBar.Hello

@HaloFour
Copy link

HaloFour commented Jun 9, 2016

@Liero

Representing it in C# isn't the problem, it's representing it in the CLR. That "interface" can't actually exist as an interface today. You couldn't declare parameters or generic arguments of that "interface". The C# compiler could fake it within the confines of a method body but that would be about it.

I'm not arguing that these features shouldn't be implemented. I like intersection types (less keen on union types *, but I'm not opposed to the idea, just like to see how it would work). My opinion is that if they are to be done that they should be done right, including proper support for them in the CLR so that they can be used anywhere normal types can be used and without a performance penalty.

* I do think that union types would be great for exception handlers:

class Exception1 : Exception {
    string Foo { get; }
}

class Exception2 : Exception {
    string Foo { get; }
}

try { ... }
catch (Exception1 | Exception2 exception) {
    var foo = exception.Foo; // can reference members common to both interfaces here
    ...
}

I also think that both intersection and union types would be great in pattern matching, either implemented as proper types or as special patterns.

@yufeih
Copy link
Contributor

yufeih commented Jun 11, 2016

Union types are also widely used.

In StackExchange.Redis, a RedisKey is union type of string and byte[], a RedisValue is a union type of bool, int, string.. etc.

Task<bool> StringSetAsync(RedisKey key, RedisValue value)
Task<bool> StringSetAsync(string | byte[] key, RedisValue value)
Task<bool> StringSetAsync(string | byte[] key, string | int | int? | bool | bool? /* ... */ value)

While RedisKey fits nicely, RedisValue probably deserves it's own type and continue using implicit conversion operators. So the pattern of implementing union types already exists:

public class RedisValue
{
    public static implicit operator RedisValue(int value);
    public static implicit operator RedisValue(int? value);
    // more implicit operators...
}

What is left is Intellisence. Intellisence does not show you possible implicitly convertible types of a function parameter. This makes it hard to discover what can be passed to a function when there is an implicit conversion. It can be made to do so without much effort:

@Thaina
Copy link

Thaina commented Sep 23, 2016

2-3 related #2146 #3255 #13488

@Thaina
Copy link

Thaina commented Sep 23, 2016

1 related #9595

@ufcpp
Copy link
Contributor

ufcpp commented Sep 23, 2016

@rexxiang
Copy link

I'm just a little curious. why all these features already are supported in F#, and run in the same CLR?

@iam3yal
Copy link

iam3yal commented Nov 16, 2016

@rexxiang F# does things differently and willing to go pretty far in order to give the developer what they want regardless to whether there's CLR support for it so they do pretty funky things to get things done whereas C# is more conservative in that features that require no CLR support would be prioritized first (at least from what I've seen) and features that do require CLR support might be deferred for when CLR changes are pushed and allow feature X to be implemented more efficiently and effectively with no hacks/workarounds to circumvent the CLR, all this regardless to whether it's useful enough, solve a chunk of problems and make sense to the theme of the language.

Sometimes features require more discussions and stuff so these may also get pushed to some other version of the language.

Finally F# came after C# this allowed the design team more freedom and also to make some design changes that in C# would be a breaking change and last but not least C# and F# are two different languages so some features might not be available to C# or vice-versa regardless to the CLR.

I'm just a peon here so this is all just my own observation. 😄

@gafter
Copy link
Member

gafter commented Mar 24, 2017

We are now taking language feature discussion in other repositories:

Features that are under active design or development, or which are "championed" by someone on the language design team, have already been moved either as issues or as checked-in design documents. For example, the proposal in this repo "Proposal: Partial interface implementation a.k.a. Traits" (issue 16139 and a few other issues that request the same thing) are now tracked by the language team at issue 52 in https://github.com/dotnet/csharplang/issues, and there is a draft spec at https://github.com/dotnet/csharplang/blob/master/proposals/default-interface-methods.md and further discussion at issue 288 in https://github.com/dotnet/csharplang/issues. Prototyping of the compiler portion of language features is still tracked here; see, for example, https://github.com/dotnet/roslyn/tree/features/DefaultInterfaceImplementation and issue 17952.

In order to facilitate that transition, we have started closing language design discussions from the roslyn repo with a note briefly explaining why. When we are aware of an existing discussion for the feature already in the new repo, we are adding a link to that. But we're not adding new issues to the new repos for existing discussions in this repo that the language design team does not currently envision taking on. Our intent is to eventually close the language design issues in the Roslyn repo and encourage discussion in one of the new repos instead.

Our intent is not to shut down discussion on language design - you can still continue discussion on the closed issues if you want - but rather we would like to encourage people to move discussion to where we are more likely to be paying attention (the new repo), or to abandon discussions that are no longer of interest to you.

If you happen to notice that one of the closed issues has a relevant issue in the new repo, and we have not added a link to the new issue, we would appreciate you providing a link from the old to the new discussion. That way people who are still interested in the discussion can start paying attention to the new issue.

Also, we'd welcome any ideas you might have on how we could better manage the transition. Comments and discussion about closing and/or moving issues should be directed to #18002. Comments and discussion about this issue can take place here or on an issue in the relevant repo.

@gafter gafter closed this as completed Mar 24, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

8 participants