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

If no one insist, I started working on this.

tinganho avatar Aug 13 '16 13:08 tinganho

What's your thought about type safety inside the function, i.e. ensure a return statement returns something assignable to a return type?

interface A {
     a: string;
}
function f(p: string): A[p] {
    return 'aaa'; // This is string, but can we ensure it is the intended A[p] ?
}

tinganho avatar Aug 14 '16 03:08 tinganho

Also the name "Property Type" used here seems a bit incorrect. It sort of states that the type has properties, which nearly all types have.

What about "Property Referenced Type"?

tinganho avatar Aug 14 '16 03:08 tinganho

What's your thought about type safety inside the function

My brainstorming:

let a: A;
function f(p: string): A[p] {
  let x = a[p]; // typeof A[p], only when:
  // 1. p is directly referencing function argument
  // 2. function return type is Property Reference Type

  p = "abc"; // not allowed to assign a new value when p is used on Property Reference Type

  return x; // x is A[p], so okay
}

And disallow normal string on the return line.

saschanaz avatar Aug 14 '16 04:08 saschanaz

@malibuzios problem with your idea is that it requires specifying all the generics in case they're not possible to infer, which can be viral / polluting the code-base.

niieani avatar Aug 14 '16 09:08 niieani

Any comments from the TS team about https://github.com/Microsoft/TypeScript/issues/1295#issuecomment-239653337?

@RyanCavanaugh @mhegazy etc?

tinganho avatar Aug 18 '16 09:08 tinganho

Regarding the name, I started calling this feature (at least the form that @Artazor proposed) "Indexed Generics"

spion avatar Aug 18 '16 15:08 spion

A solution from another angle of view could be for this problem. I'm not sure if it's been brought already, it's a long thread. Developing a string generic suggestion, we could extend indexation signature. Since string literals can be used for indexer type, we could have these to be equivalent (as I know they're not at the moment):

interface A1 {
    a: number;
    b: boolean;
}
interface A2 {
    [index: "a"]: number;
    [index: "b"]: boolean;
}

So, we could just write then

declare function pluck<P, T extends { [indexer: P]: R; }, R>(obj: T, p: P): R;

There're a few things need to consider:

  • how to indicate that P can only be a string literal?
    • since string technically extends all string literals, P extends string wouldn't be a very ideomatic
    • other discussion is happening about allowing P super string constraint (#7265, #6613, https://github.com/Microsoft/TypeScript/issues/6613#issuecomment-175314703)
    • do we really need to care about this? we can use whatever acceptable for indexer type - if T has an indexer of strings or numbers. then P can be string or number.
  • currently, if we pass "something" as a second argument, it will be of type string
    • string literals #10195 could be the answer
    • or TS could infer that a more specific P should be used if it's acceptable
  • indexers are implicitly optional { [i: string]: number /* | undefined */ }
    • how to enforce if we really don't want to have undefined in the domain?
  • automatic type inference for all relations between P, T and R is a key to make it work

Igorbek avatar Aug 18 '16 16:08 Igorbek

@weswigham @mhegazy, and I have been discussing this recently; we'll let you know any developments we run into, and keep in mind this is just having prototyped the idea.

Current ideas:

  • A keysof Foo operator to grab the union of property names from Foo as string literal types.
  • A Foo[K] type which specifies that for some type K that is a string literal types or union of string literal types.

From these basic blocks, if you need to infer a string literal as the appropriate type, you can write

function foo<T, K extends keysof T>(obj: T, key: K): T[K] {
    // ...
}

Here, K will be a subtype of keysof T which means that it is a string literal type or a union of string literal types. Anything you pass in for the key parameter should be contextually typed by that literal/union of literals, and inferred as a singleton string literal type.

For instance

interface HelloWorld { hello: any; world: any; }

function foo<K extends keysof HelloWorld>(key: K): K {
    return key;
}

// 'x' has type '"hello"'
let x = foo("hello");

Biggest issue is that keysof often needs to "delay" its operation. It is too eager in how it evaluates a type, which is a problem for type parameters like in the first example I posted (i.e. the case we really want to solve is actually the hard part :smile:).

Hope that gives you all an update.

DanielRosenwasser avatar Aug 18 '16 16:08 DanielRosenwasser

@DanielRosenwasser Thanks for the update. I just saw @weswigham submitted a PR about the keysof operator, so it is maybe better to hand this issue off to you guys.

I just wonder why you decided to depart from the original proposed syntax?

function get(prop: string): T[prop];

and introduce keysof?

tinganho avatar Aug 20 '16 16:08 tinganho

T[prop] is less general, and requires a lot of interlaced machinery. One big question here is how you'd even relate the literal contents of prop to property names of T. I'm not even completely sure what you'd do. Would you add an implicit type parameter? Would you need to change contextual typing behavior? Would you need to add something special to signatures?

The answer is probably yes to all of those things. I drove us away from that because my gut told me it was better to use two simpler, separate concepts and build up from there. The downside is there is a little bit more boilerplate in certain cases.

If there are newer libraries that uses these sorts of patterns and that boilerplate is making it hard for them to write in TypeScript, then maybe we should consider that. But overall this feature is primarily meant to serve library consumers, because the use-site is where you get the benefits here anyway.

DanielRosenwasser avatar Aug 20 '16 17:08 DanielRosenwasser

@DanielRosenwasser Having barely went down the rabbit hole. I still can't find any problems with implementing @SaschaNaz idea? I think keysof is redundant in this case. T[p] already relates that p must be one of the literal props of T.

My rough implementation thought was to introduce a new type called PropertyReferencedType.

export interface PropertyReferencedType extends Type {
        property: Symbol;
        targetType: ObjectType;
}

When entering a function declared with a return type that is of PropertyReferencedType or entering a function that references PropertyReferencedType: A type of a ElementAccessExpression will be augmented with a property that references the symbol of the accessed property.

export interface Type {
        flags: TypeFlags;                // Flags
        /* @internal */ id: number;      // Unique ID
        //...
        referencedProperty: Symbol; // referenced property
}

So a type with a referenced property symbol is assignable to a PropertyReferencedType. During checking, the referencedProperty must correspond to p in T[p]. Also the parent type of a element access expression must be assignable to T. And to make things easier p must also be const.

The new typePropertyReferencedType only exists inside the function as an "unresolved type". On call site one have to resolve the type with p:

interface A { a: string }
declare function getProp(p: string): A[p]
getProp('a'); // string

A PropertyReferencedType only propagates through function assignments and cannot propagate through call expressions, because a PropertyReferencedType is only a temporary type meant to help with checking the body of a function with return type T[p].

tinganho avatar Aug 30 '16 09:08 tinganho

If you introduce keysof and T[K] type operators, would it mean we could use them like this:

interface A {
  a: number;
  b: string;
}
type AK = keysof A; // "a" | "b"
type AV = A[AK]; // number | string ?
type AA = A["a"]; // number ?
type AB = A["b"]; // string ?
type AC = A["c"]; // error?
type AN = A[number]; // error?

type X1 = keysof { [index: string]: number; }; // string ?
type X2 = keysof { [index: string]: number; [index: number]: string; }; // string | number ?

@DanielRosenwasser wouldn't your example have the same meaning with my

function foo<T, K extends keysof T>(obj: T, key: K): T[K] {
    // ...
}
// same as ?
function foo<K, V, T extends { [k: K]: V; }>(obj: T, key: K): V {
    // ...
}

Igorbek avatar Sep 02 '16 00:09 Igorbek

I am not seeing how the signature would be written for Underscore's _.pick:

o2 = _.pick(o1, 'p1', 'p2');

pick(Object, ...props: String[]) : WHAT GOES HERE;

rtm avatar Sep 12 '16 02:09 rtm

@rtm I suggested it in https://github.com/Microsoft/TypeScript/issues/1295#issuecomment-234724380. Though it might be better to open a new issue, even though it is related to this one.

tinganho avatar Sep 12 '16 04:09 tinganho

Implementation now available in #11929.

ahejlsberg avatar Nov 02 '16 16:11 ahejlsberg