TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Suggestion: Type Property type

Open fdecampredon opened this issue 12 years ago • 76 comments

Motivations

A lot of JavaScript library/framework/pattern involve computation based on the property name of an object. For example Backbone model, functional transformation pluck, ImmutableJS are all based on such mechanism.

//backbone
var Contact = Backbone.Model.extend({})
var contact = new Contact();
contact.get('name');
contact.set('age', 21);

// ImmutableJS
var map = Immutable.Map({ name: 'François', age: 20 });
map = map.set('age', 21);
map.get('age'); // 21

//pluck
var arr = [{ name: 'François' }, { name: 'Fabien' }];
_.pluck(arr, 'name') // ['François', 'Fabien'];

We can easily understand in those examples the relation between the api and the underlying type constraint. In the case of the backbone model, it is just a kind of proxy for an object of type :

interface Contact {
  name: string;
  age: number;
}

For the case of pluck, it's a transformation

T[] => U[]

where U is the type of a property of T prop.

However we have no way to express such relation in TypeScript, and ends up with dynamic type.

Proposed solution

The proposed solution is to introduce a new syntax for type T[prop] where prop is an argument of the function using such type as return value or type parameter. With this new type syntax we could write the following definition :

declare module Backbone {

  class Model<T> {
    get(prop: string): T[prop];
    set(prop: string, value: T[prop]): void;
  }
}

declare module ImmutableJS {
  class Map<T> {
    get(prop: string): T[prop];
    set(prop: string, value: T[prop]): Map<T>;
  }
}

declare function pluck<T>(arr: T[], prop: string): Array<T[prop]>  // or T[prop][] 

This way, when we use our Backbone model, TypeScript could correctly type-check the get and set call.

interface Contact {
  name: string;
  age: number;
}
var contact: Backbone.Model<Contact>;

var age = contact.get('age');
contact.set('name', 3) /// error

The prop constant

Constraint

Obviously the constant must be of a type that can be used as index type (string, number, Symbol).

Case of indexable

Let's give a look at our Map definition:

declare module ImmutableJS {
  class Map<T> {
    get(prop: string): T[string];
    set(prop: string, value: T[string]): Map<T>;
  }
}

If T is indexable, our map inherit of this behavior:

var map = new ImmutableJS.Map<{ [index: string]: number}>;

Now get has for type get(prop: string): number.

Interrogation

Now There is some cases where I have pain to think of a correct behavior, let's start again with our Map definition. If instead of passing { [index: string]: number } as type parameter we would have given { [index: number]: number } should the compiler raise an error ?

if we use pluck with a dynamic expression for prop instead of a constant :

var contactArray: Contact[] = []
function pluckContactArray(prop: string) {
  return _.pluck(myArray, prop);
}

or with a constant that is not a property of the type passed as parameter. should the call to pluck raise an error since the compiler cannot infer the type T[prop], shoud T[prop] be resolved to {} or any, if so should the compiler with --noImplicitAny raise an error ?

fdecampredon avatar Nov 28 '14 15:11 fdecampredon

I think we should rely on a more general and less verbose syntax as defined in #3779.

interface Map<T> {
  get<A>(prop: $Member<T,A>): A;
  set<A>(prop: $Member<T,A>, value: A): Map<T>;
}

Or is it not possibe to infer the type of A?

Lenne231 avatar Aug 02 '15 10:08 Lenne231

Just want to say that I made a little codegen tool to make TS integration with ImmutableJS easier while we are waiting for the normal solution: https://www.npmjs.com/package/tsimmutable. It is quite simple, but I think it will work for most use cases. Maybe it will help someone.

s-panferov avatar Aug 02 '15 11:08 s-panferov

Also I want to note, that the solution with a member type may not work with ImmutableJS:

interface Profile {
  firstName: string 
}

interface User {
  profile: Profile  
}

let a: Map<User> = fromJS(/* ... */);
a.get('profile') // Type will be Profile, but the real type is Map<Profile>!

s-panferov avatar Aug 02 '15 11:08 s-panferov

@s-panferov Something like this could work:

interface ImmutableMap<T> {
    get<A extends boolean | number | string>(key : string) : A;
    get<A extends {}>(key : string) : ImmutableMap<A>;
    get<E, A extends Array<any>>(key : string) : ImmutableList<E>;
}

interface Profile {

}

interface User {
    name : string;
    profile : Profile;
}

var map : ImmutableMap<User>;

var name = map.get<string>('name'); // string
var profile = map.get<Profile>('profile'); // ImmutableMap<Profile>

This won't exclude DOM nodes or Date objects but it shouldn't be allowed to use them in immutable structures at all. https://github.com/facebook/immutable-js/wiki/Converting-from-JS-objects

Lenne231 avatar Aug 02 '15 17:08 Lenne231

Gradually working from the best workaround

I think it is useful to first start with the best currently available workaround, and then gradually work it out from there.

Let's say we need a function that returns the value of a property for any containing non-primitive object:

function getProperty<T extends object>(container: T; propertyName: string) {
    return container[propertyName];
}

Now we want the return value to have the type of the target property, so another generic type parameter could be added for its type:

function getProperty<T extends object, P>(container: T; propertyName: string) {
    return <P> container[propertyName];
}

So a use case with a class would look like:

class C {
    member: number;
    static member: string;
}

let instance = new C();
let result = getProperty<C, typeof instance.member>(instance, "member");

And result would correctly receive the type number.

However, there seems to be a duplicate reference to 'member' in the call: one is in the type parameter, and the other one is a literal string that will always receive the string representation of the target property name. The idea of this proposal is that these two can be unified to a single type parameter that would only receive the string representation.

So it needs to be observed here that the string would also act as a generic parameter, and will need be passed as a literal for this to work (other cases could silently ignore its value unless some form of runtime reflection is available). So to make the semantics clear, there needs to be some way to signify a relation between the generic parameter and the string:

function getProperty<T extends object, PName: string = propertyName>(container: T; propertyName: string) {
    return <T[PName]> container[propertyName];
}

And now the calls would look like:

let instance = new C();
let result = getProperty<C>(instance, "member");

Which would internally resolve to:

let result = getProperty<C, "member">(instance, "member");

However since C contains both an instance and static property named member, the higher-kind generic expression T[PName] is ambiguous. Since the intention here is mostly to apply it to properties of instances, a solution like the proposed typeon operator could be used internally, which may also improve the semantics as T[PName] is interpreted by some as representing a value reference, not necessarily a type:

function getProperty<T extends object, PName: string = propertyName>(container: T; propertyName: string) {
    return <typeon T[PName]> container[propertyName];
}

(This would also work if T is a compatible interface type, as typeon supports interfaces as well)

To get the static property, the function would be called with the constructor itself and the constructor type should be passed as typeof C:

let result = getProperty<typeof C>(C, "member"); // Note it is called with the constructor object

(Internally typeon (typeof C) resolves to typeof C so this would work) result will now correctly receive the type string.

To support additional types of property identifiers, this can be rewritten as:

type PropertyIdentifier = string|number|Symbol;

function getProperty<T extends object, PName: PropertyIdentifier = propertyName>(container: T; propertyName: PropertyIdentifier) {
    return <typeon T[PName]> container[propertyName];
}

So there are several different features that are needed to support this:

  • Allow literal values to be passed as generic parameters.
  • Allow those literals to receive the value of function arguments.
  • Allow a form of higher kind generics.
  • Allow referencing a property type through a literal generic parameter on a generic type through higher kind generics.

Rethinking the problem

Now let's get back to the original workaround:

function getProperty<T extends object, P>(container: T; propertyName: string) {
    return <P> container[propertyName];
}

There is one advantage about this workaround, is that it can be easily extended to support more complex path names, referencing not only direct properties, but properties of nested objects:

function getPath<T extends object, P>(container: T; path: string) {
    ... more complex code here ...

    return <P> resultValue;
}

and now:

class C {
    a: {
        b: {
            c: string[];
        }
    }
}
let instance = new C();
let result = getPath<C, typeof instance.a.b.c>(instance, "a.b.c");

result would correctly get the type string[] here.

The question is, should nested paths be supported as well? Will the feature be really that useful if no auto-completion is available when typing them?

This suggests that a different solution might be possible, which would work in the other direction. Back to the original workaround:

function getProperty<T extends object, P>(container: T; propertyName: string) {
    return <P> container[propertyName];
}

Looking at this from the other direction, it is possible to take the type reference itself and convert it to a string:

function getProperty<T extends object, P>(container: T; propertyName: string = @typeReferencePathOf(P)) {
    return <P> container[propertyName];
}

@typeReferencePathOf is similar in concept to nameOf but applies to generic parameters. It would take the received type reference typeof instance.member (or alternatively typeon C.member), extract the property path member, and convert it to the literal string "member" at compile time. A less specialized complementary @typeReferenceOf would resolve to the complete string "typeof instance.member".

So now:

getProperty<C, typeof instance.subObject>(instance);

Would resolve to:

getProperty<C, typeof instance.subObject>(instance, "subObject");

And a similar implementation for getPath:

getPath<C, typeof instance.a.b.c>(instance);

Would resolve to:

getPath<C, typeof instance.a.b.c>(instance, "a.b.c");

Since @typeReferencePathOf(P) is only set as a default value. The argument can be stated manually if needed:

getPath<C, SomeTypeWhichIsNotAPath>(instance, "member.someSubMember.AnotherSubmember.data");

If the second type parameter would not be provided @typeReferencePathOf() could resolve to undefined or alternatively the empty string "". If a type was provided but did not have an internal path, it would resolve to "".

Advantages of this approach:

  • Does not require higher-kind generics.
  • Does not require allowing literals as generic parameters.
  • Does not require extending generics in any way.
  • Allows auto-completion when typing the typeof expression and uses an existing mechanism of type checking to validate it instead of needing to convert it from a string representation at compile-time.
  • Can be used within generic classes as well.
  • Does not require typeon (but could support it).
  • Can be applied in other scenarios.

rotemdan avatar Sep 15 '15 08:09 rotemdan

+1

niieani avatar Jan 30 '16 13:01 niieani

Nice! I've already started to write a big proposal to address the same problem, but found this discussion, so let's discuss here.

Here is an extract from my not-submitted issue:

Question: How the following function should be declared in .d.ts to be usable in contexts where it is supposed to be used?

function mapValues(obj, fn) {
      return Object.keys(obj)
          .map(key => ({key, value: fn(obj[key], key)}))
          .reduce((res, {key, value}) => (res[key] = value, res), {})
}

This function (with slight variations) could be found in almost every generic "utils" library.

There are two distinct use cases of the mapValues in the wild:

a. Object-as-a-_Dictionary_ where property names are dynamic, values has the same one type, and the function is in general case monomorphic (aware of this type)

var obj = {'a': 1, 'b': 2, 'c': 3};
var res = mapValues(x, val => val * 5); // {a: 5, b: 10, c: 15}
console.log(res['a']) // 5

b. Object-as-a-_Record_ where each property has its own type, while the function is parametrically polymorphic (by implementation)

var obj = {a: 123, b: "Hello", c: true};
var res = mapValues(p, val => [val]); // {a: [123], b: ["Hello"], c: [true]}
console.log(res.a[0].toFixed(2)) // "123.00"

The best available instrumentation for the mapValues with current TypeScript is:

declare function mapValues<T1, T2>(
    obj: {[key: string]: T1},
    fn: (arg: T1, key: string) => T2
): {[key: string]: T2};

It's not hard to see that this signature perfectly matches to the Object-as-a-_Dictionary_ use-case, while produces a somewhat surprising1 result of the type inference when being applied in the case where Object-as-a-_Record_ was the intention.

The type {p1: T1, p2: T2, ...pn: Tn} will be coerced to the {[key: string]: T1 | T2 | ... | Tn } conflating all the types and effectively discarding all the information about the structure of a record:

  • the correct and expected2 to be fine console.log(res.a[0].toFixed(2)) will be rejected by the compiler;
  • the accepted console.log((<number>res['a'][0]).toFixed(2)) has two uncontrolled and error-prone places: the type-cast and arbitrary property name.

1, 2 — for the programmers who migrates from the ES to TS


Possible steps to address this problem (and solve others, as well)

1. Introduce variadic records with help of string literal types

type Numbers<p extends string> =  { ...p: number };
type NumbersOpt<p extends string> = {...p?: number };
type ABC = "a" | "b" | "c";
type abc = Numbers<ABC> // abc =  {a: number, b: number, c: number} 
type abcOpt = NumbersOpt<ABC> // abcOpt =  {a?: number, b?:number, c?: number}

function toFixedAll<p extends string>(obj: {...p: number}, precision):{...p: string}  {
      var result: {...p: string} = {} as any;
      Object.keys(obj).forEach((p:p) => {
           result[p] = obj[p].toFixed(precision);
      });
      return result;
}

var test = toFixedAll({x:5, y:7}, 3); // { x: "5.00", y: "6.00" },  p inferred as "x"|"y"
console.log(test.y.length) // 4   test.y: string
2. Allow formal types to be subscripted with other formal types that are constrained to extend 'string'

example:


declare function mapValues<p extends string, T1[p], T2[p]>(
     obj:{...p: T1[p]}, fn:(arg: T1[p]) => T2[p]
): {...p: T2[p]};
3. Allow destructuring of formal types

example:

class C<Array<T>> {
     x: T;
}   

var v1: C<string[]>;   // v1.x: string

with all three steps together we could write

declare module Backbone {

  class Model<{...p: T[p]}> {
    get(prop: p): T[p];
    set(prop: p, value: T[p]): void;
  }
}

declare module ImmutableJS {
  class Map<{...p: T[p]}> {
    get(prop: p): T[p];
    set(prop: p, value: T[p]): this;
  }
}

declare function pluck<p extends string, T[p]>(
    arr: Array<{...p:T[p]}>, prop: p
): Array<T[p]> 

I know that the syntax is more verbose than the one proposed by @fdecampredon but I can't imagine how to express the type of the mapValues or the combineReducers with the original proposal.

function combineReducers(reducers) {
  return (state, action) => mapValues(reducers, (reducer, key) => reducer(state[key], action))
}

with my proposal its declaration will look like:

declare function combineReducers<p extends string, S[p]>(
    reducers: { ...p: (state: S[p], action: Action) => S[p] }
): (state: { ...p: S[p] }, action: Action) => { ...p: S[p] };

Is it expressible with the original proposal?

@spion, @fdecampredon ?

Artazor avatar Jan 30 '16 20:01 Artazor

@Artazor Definitely an improvement. It now seems to be good enough to express my benchmark use case of this feature:

Assuming user.id and user.name are database column types containing number and string accordingly i.e. Column<number> and Column<string>

Write the type of a function select that takes:

select({id: user.id, name: user.name})

and returns Query<{id: number; name: string}>

select<T>({...p: Column<T[p]>}):Query<T>

Not sure hows that going to be checked and inferred though. Seems like there might be a problem, as the type T doesn't exist. Would the return type need to be expressed in a destructured form? i.e.

select<T>({...p: Column<T[p]>}):Query<{...p:T[p]}>

spion avatar Feb 03 '16 15:02 spion

@Artazor forgot to ask, is the p extends string parameter really necessary?

Wouldn't something like this be enough?

select<T[p]>({...p: Column<T[p]>}):Query<{...p:T[p]}>

i.e. for all type variables T[p] in {...p:Column<T[p]>}

edit: another question, how is this going to be checked for correctness?

spion avatar Feb 08 '16 15:02 spion

@spion I've got your point of view — you've misunderstood me (but it's my fault), by the T[p] I've meant an entirely different thing, and you will see that p extends string is a crucial thing here. Let me explain my thoughts in depth.

Let's consider four use cases for data structures: List, Tuple, Dictionary and Record. We'll refer to them as conceptual data structures and describe them with the following properties:

Conceptual data structuresAccess by
a. position
(number)
b. key
(string)
Count of
items
1. variable
(the same role for each item)
ListDictionary
2. fixed
(each item plays its own unique role)
TupleRecord

In JavaScript, these four cases are backed by two storage forms: an Array — for a1 and a2, and an Object — for b1 and b2.

_Note 1_. To be honest, it is not correct to say that the Tuple is backed by the Array, as the only "true" tuple type is the type of the arguments object which is not an Array. Nevertheless, they are more or less interchangeable, especially in the context of the destructuring and the Function.prototype.apply which opens the door for the meta-programming. The TypeScript also leverages Arrays for modeling Tuples.

_Note 2_. While the full concept of the Dictionary with arbitrary keys was introduced decades later in form of the ES6 Map, Brendan Eich's initial decision to conflate a Record and a limited Dictionary (with string keys only) under the same hood of Object (where obj.prop is equivalent to the obj["prop"]) became the most controversial element of the entire language (in my opinion). It is both the curse and the blessing of the JavaScript semantics. It makes reflection trivial and encourages programmers freely switch between programming and meta-programming levels at almost zero mental cost (even without noticing!). I believe it is the essential part of the JavaScript success as the scripting language.

Now it is the time for the TypeScript to provide the way for expressing types for this weird semantics. When we think at the programming level all is ok:

Types at the programming levelAccess by
a. position
(number)
b. key
(string)
Count of
items
1. variable
(the same role for each item)
T[]{[key:string]:T}
2. fixed
(each item plays its own unique role)
[T1, T2, ...]{key1: T1, key2: T2, ...}

However, when we switch to the meta-programming level, then things that were fixed at the programming level suddenly become variable! And here we suddenly recognize relations between tuples and function signatures and propose things like #5453 (Variadic Kinds) that in fact covers only small (but quite important) part of the metaprogramming needs — the concatenation of signatures by giving the ability to destructure a formal parameter into types of the rest-args:

     function f<T>(a: number, ...args:T) { ... }

    f<[string,boolean]>(1, "A", true);

In case, if #6018 also will be implemented, the Function class could look like

declare class Function<This, TArgs, TRes> {
        This::(...args: TArgs): TRes;
        call(self: This, ...args: TArgs): TRes;
        apply(self: This, args: TArgs): TRes;
        // bind needs also formal pattern matching:
        bind<[...TPartial, ...TCurried] = TArgs>(
           self: This, ...args: TPartial): Function<{}, TCurried, TRes> 
}

It is great but anyway incomplete.

For example, imagine that we want to assign a correct type to the following function:

function extractAndWrapAll(...args) {
     return args.map(x => [x]);
}

// wrapAll(1,"A",true) === [[1],["A"],[true]]

With proposed variadic kinds we can't transform types of the signature. Here we need something more powerful. In fact, it is desirable to have compile-time functions that can operate over types (as in Facebook's Flow). Though, I'm sure this will be possible only when (and if) the type system of the TypeScript would be stable enough to expose it to the end programmers without significant risk to break a user-land on a next minor update. Thus, we need something less radical than the full meta-programming support but still capable of dealing with demonstrated problems.

To address this problem, I want to introduce the notion of object signature. Roughly it is either

  1. the set of the property names of the object, or
  2. the set of the keys of the dictionary, or
  3. the set of the numeric indexes of an array
  4. the set of numeric positions of a tuple.

Ideally, it would be nice to have an integer literal types as well as string literal types to represent signatures of the arrays or tuples like

type ZeroToFive = 0 | 1 | 2 | 3 | 4 | 5;
// or
type ZeroToFive = 0 .. 5;   // ZeroToFive extends number (!)

the rules for integer literals are congruent to the string literal ones;

Then we can introduce signature abstraction syntax, that exactly matches to the object rest/spread syntax:

{...Props: T }

with one significant exception: here Props is the identifier that is bound under the universal quantifier:

<Props extends string> {...Props: T }  // every property has type T
<Index extends number> {...Index: T }  // every item has type T  
// the same as T[]

thus, it is introduced in type lexical scope and can be used anywhere in this scope as the name of the type. However, its usage is dual: when used in place of rest/spread property name it represents abstraction over the object signature when it is used a standalone type it represents a subtype of the string (or number respectively).

declare class Object {
      static keys<p extends string, q extends p>(object{...q: {}}): p[];
}

And here is the most sophisticated part: Key Dependent Types

we introduce special type construct: T for Prop (I'd like to use this syntax rather than T[Prop] that confused you) where Prop is the name of the type variable that holds object's signature abstraction. For example <Prop extends string, T for Prop> introduces two formal types into type lexical scope, the Prop and the T where it is known that for each particular value p of Prop there will be it's own type T.

We do not say that somewhere is an object that has properties Props and their types are T ! We only introduce a functional dependency between two types. Type T is correlated with members of type Props, and that's all!

It gives us possibility to write such things as

function unwrap<P extends string, T for P>(obj:{...P: Maybe<T>}): Maybe<{...P: T}> {
  ...
}

unwrap({a:{value:1}, b:{value:"A"}, c:{value: true}}) === { a: 1, b: "A", c: true }
// here actual parameters will be inferred as 
unwrap<"a"|"b"|"c", {a: number, b: string, c: boolean}>

however the second parameter is treated not as an object but rather as the abstract map of identifiers to types. In this perspective T for P can be used to represent abstract sequences of types for tuples when P is subtype of number (@JsonFreeman ?)

When T is used somewhere inside {...P: .... T .... } it represents exactly one particular type of that map.

It is my main idea. Eagerly awaiting any questions, thoughts, criticism -)

Artazor avatar Feb 09 '16 06:02 Artazor

Right, so extends string is to take arrays (and variadic arguments) into account in one case, and string constants (as types) in the other. Sweet!

We do not say that somewhere is an object that has properties Props and their types are T ! We only introduce a functional dependency between two types. Type T is correlated with members of type Props, and that's all!

I didn't mean that, I meant it more as their types are T[p], a dictionary of types indexed by p. If thats a good intuition, I'd keep that.

Overall though, the syntax might need a bit more work, but the general idea looks awesome.

~~Is it possible to write unwrap for variadic arguments?~~

edit: nevermind, I just realised that your proposed extension to variadic kinds addresses this.

spion avatar Feb 09 '16 10:02 spion

Hello everybody, I am puzzling how to solve one of my problem and found this discussion. Problem is: I have RpcManager.call(command:Command):Promise<T> method, and usage would be so:

RpcManager.call(new GetBalance(123)).then((result) => {
 // here I want that result would have a type.
});

Solution I think could be like:

interface Command<T> {
    responseType:T;
}

class GetBalance implements Command<number> {
    responseType: number; // somehow this should be avoided. maybe Command should be abstract class.
    constructor(userId:number) {}
}

class RpcManager {
    static call(command:Command):Promise<typeof command.responseType> {
    }
}

or:

class RpcManager {
    static call<T>(command:Command<T>):Promise<T> {
    }
}

Any thoughts on this?

antanas-arvasevicius avatar Feb 20 '16 21:02 antanas-arvasevicius

@antanas-arvasevicius the last code block in that example should do what you want.

it sounds like you have more of a question of how to accomplish a specific task; please use Stack Overflow or file an issue if you think you have found a compiler bug.

RyanCavanaugh avatar Feb 22 '16 20:02 RyanCavanaugh

Hi, Ryan, thank you for your response. I've tried that last block of code but it doesn't work.

Quick demo:

interface Command<T> { }
class MyCommand implements Command<{status:string}> { }
class RPC { static call<T>(command:Command<T>):T { return; } }

let response = RPC.call(new MyCommand());
console.log(response.status);

//output: error TS2339: Property 'status' does not exist on type '{}'.
//tested with: Version 1.9.0-dev.20160222

Sorry that I didn't use Stack Overflow, but I thought that it was related to this issue :) Should I open an new issue about this topic?

antanas-arvasevicius avatar Feb 22 '16 21:02 antanas-arvasevicius

An unconsumed generic type parameter prevents inference from working; in general you should never have unused type parameters in type declarations as they are meaningless. If you consume T, everything just works:

interface Command<T> { foo: T }
class MyCommand implements Command<{status:string}> { foo: { status: string; } }
class RPC { static call<T>(command:Command<T>):T { return; } }

let response = RPC.call(new MyCommand());
console.log(response.status);

RyanCavanaugh avatar Feb 22 '16 21:02 RyanCavanaugh

That is just amazing! Thank you! I haven't thought that type parameter can be placed inside generic type and TS will extract it. On Feb 22, 2016 11:56 PM, "Ryan Cavanaugh" [email protected] wrote:

An unconsumed generic type parameter prevents inference from working; in general you should never have unused type parameters in type declarations as they are meaningless. If you consume T, everything just works:

interface Command { foo: T }class MyCommand implements Command<{status:string}> { foo: { status: string; } }class RPC { static call(command:Command):T { return; } } let response = RPC.call(new MyCommand()); console.log(response.status);

— Reply to this email directly or view it on GitHub https://github.com/Microsoft/TypeScript/issues/1295#issuecomment-187404245 .

antanas-arvasevicius avatar Feb 22 '16 22:02 antanas-arvasevicius

@antanas-arvasevicius if you are creating RPC style APIs I have some docs you might find useful : https://github.com/alm-tools/alm/blob/master/docs/contributing/ASYNC.md :rose:

basarat avatar Feb 22 '16 22:02 basarat

Approaches above seem:

  • quite complicated;
  • don't tackle the usage of strings in code. string are not "Find all references"-able, nor refactorable (e.g. renames).
  • some only support "1st level" properties and not more complex expressions (which are supported by some frameworks).

Here's another idea, inspired by C# Expression trees. This is just a rough idea, nothing fully thought-out! Syntax is terrible. I just want to see if this inspires someone.

Assume we have a special kind of strings to denote expressions. Let's call it type Expr<T, U> = string. Where T is the starting object type and U is the result type.

Assume we could create an instance of Expr<T,U> by using a lambda that takes one parameter of type T and performs a member access on it. For example: person => person.address.city. When this happens, the whole lambda is compiled to a string containing whatever access on the parameter was, in this case: "address.city".

You can use a plain string instead, which would be seen as Expr<any, any>.

Having this special Expr type in the language enables stuff like that:

function pluck<T, U>(array: T[], prop: Expr<T, U>): U[];

let numbers = pluck([{x: 1}, {x: 2}], p => p.x);  // number[]
// compiles to:
// let numbers = pluck([..], "x");

This is basically a limited form of what Expressions are used in C# for. Do you think this could be refined and lead somewhere interesting?

jods4 avatar Mar 22 '16 20:03 jods4

@fdecampredon @RyanCavanaugh

(@jods4 - I'm sorry I'm not replying to your suggestion here. I hope it doesn't get 'buried' through the comments)

I think the naming of this feature ('Type Property type') is highly confusing and very difficult to understand. It was very hard to even figure out what the concept described here was and what it means in the first place!

First, not all types have properties! undefined and null don't (though these are only recent additions to the type system). Primitives like number, string, boolean are rarely indexed by a property (e.g. 2["prop"]? though this does seem to work, it almost always a mistake)

I would suggest naming this issue Interface property type reference through string literal values. The topic here is not about introducing a new 'type', but a very particular way to reference an existing one using a string variable or function parameter who's value must be known at compile time.

It would have been highly beneficial if this was described and exemplified as simply as possible, outside of the context of particular use case:

interface MyInterface {
  prop1: number;
  prop2: string;
}

let prop1Name = "prop1";
type Prop1Type = MyInterface[prop1Name]; // Prop1Type is now 'number'

let prop2Name = "prop2";
type Prop2Type = MyInterface[prop2Name]; // Prop2Type is now 'string'

let prop3Name = "prop3";
type NonExistingPropType = MyInterface[prop3Name]; // Compilation error: property 'prop3' does not exist on 'MyInterface'.

let randomString = createRandomString();
type NotAvailablePropType = MyInterface[randomString]; // Compilation error: value of 'randomString' is not known at compile time.

Edit: It seems like in order to implement this correctly the compiler must know for sure that the string assigned to the variable has not changed between the point it was initialized and the point it was referenced in the type expression. I don't think this is very easy? Would this assumption about the run-time behavior always hold?

Edit 2: Perhaps this would only work with const when used with a variable?

malibuzios avatar Mar 24 '16 14:03 malibuzios

I'm not sure if the original intention was to only allow the property reference at the very particular case of a string literal is passed to a function or method parameter? e.g.

function func(someString: string): MyInterface[someString] {
  ..
}

let x = func("prop"); // x gets the type of MyInterface.prop

Have I generalized this beyond the what originally intended?

How would this handle a case where the function argument is not a string literal, i.e. not known at compile time? e.g.

let x = func(getRandomString()); // What type if inferred for 'x' here?

Will it error, or default to any perhaps?

(P.S: If this was indeed the intention, then I will suggest renaming this issue to Interface property type reference by string literal function or method arguments - As lengthy as this turned out, this is much more accurate and explanatory than the current title.)

malibuzios avatar Mar 24 '16 15:03 malibuzios