Suggestion: Type Property type
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 ?
Here is a simple benchmark example (enough for an illustration) that shows what this feature needs to enable:
Write the type of this function, which:
- takes an object containing promise fields, and
- returns the same object but with all fields resolved, each field having the proper type.
function awaitObject(obj) {
var result = {};
var wait = Object.keys(obj)
.map(key => obj[key].then(val => result[key] = val));
return Promise.all(wait).then(_ => result)
}
When called on the following object:
var res = awaitObject({a: Promise.resolve(5), b: Promise.resolve("5")})
The result res should be of type {a: number; b: string}
With this feature (as fully fleshed out by @Artazor) the signature would be
awaitObject<p, T[p]>(obj: {...p: Promise<T[p]>}):Promise<{...p: T[p]}>
edit: fixed the return type above, was missing Promise<...> ^^
@spion
Thanks for trying to provide an example, but nowhere here I've found a reasonable and concise specification and a set of clear reduced examples that are detached from practical applications and try to highlight the semantics and the various edge cases of how this would work, even something as basic as:
function func<T extends object>(name: string): T[name] {
...
}
- There's been very little effort to provide an effective and explanatory title (as I've mentioned 'Type Property Type' is confusing and not very explanatory name for this feature, which is not really about any particular type but about a type reference). My best suggested title was Interface property type reference by string literal function or method arguments (assuming I did not misunderstand the scope of this).
- There has not been a clear mention of what would happen if
nameis not known at compile time, null, or undefined, e.g.func<MyType>(getRandomString()),func<MyType>(undefined). - There has not been a clear mention of what would happen if
Tis a primitive type likenumberornull. - No clear detail was provided on whether this only applies to functions and whether
T[name]can be used in the function body. And in that case, what happens ifnameis reassigned in the function body and thus its value may no longer known at compile time? - No real specification of a syntax: e.g. will
T["propName"]orT[propName]work as well by its own? without a reference to a parameter or variable, I mean - it could be useful! - No mention or discussion if
T[name]can be used in other parameters or even outside of function scopes, e.g.
function func<T extends object>(name: string, val: T[name]) {
...
}
type A = { abcd: number };
const name = "abcd";
let x: A[name]; // Type of 'x' resolves to 'number'
_7. No real discussion of the relatively simple workaround using an additional generic parameter and typeof (though it was mentioned, but relatively late after the feature had already been accepted):
function get<T, V>(obj: T, propName: string): V {
return obj[propName];
}
type MyType = { abcd: number };
let x: MyType = { abcd: 12 };
let result = get<MyType, typeof x.abcd>(x, "abcd"); // Type of 'result' is 'number'
In conclusion: There is no real proposal here, only a set of use case demonstrations. I'm surprised this has been accepted or even received positive interest by the TypeScript team at all because I wouldn't otherwise believe this would be up to their standards. I'm sorry if I may sound a bit harsh here (not typical of me) but none of my criticism is personal or directed towards any particular individual.
Do we really want to go that far out there in terms of meta-programming?
JS is a dynamic language, code can manipulate objects in arbitrary ways. There are limits to what we can model in the type system and it's easy to come up with functions that you can't model in TS. The question is rather: how far is it reasonable and useful to go?
Last example (awaitObject) from @spion is at the same time:
- Very complex from the language point of view (I agree with @malibuzios here).
- Very narrow in terms of applicability. That example choose specific constraints and does not generalize well.
BTW @spion you didn't get the return type of your example right... It returns a Promise.
We are far from the original issue, which was about typing API that take a string representing fields, such as _.pluck
Those APIs should be supported because they are commonplace and not that complicated. We don't need meta-models such as { ...p: T[p] } for that.
There are several examples in the OP, some more from Aurelia in my comment in the nameof issue.
A different approach can cover those use-cases, see my comment above for a possible idea.
@jods4 its not narrow at all. It can be used for a number of things that are impossible to model in the type system at the moment. I'd say its one of the last large missing parts in the TS type system. There are plenty of real world examples above by @Artazor https://github.com/Microsoft/TypeScript/issues/1295#issuecomment-177287714 the simpler stuff above, the sql query builder "select" example and so on.
This is awaitObject in bluebird. Its a real method. The type is currently useless.
A more general solution will be better. It will work for both the simple and the complex cases. An underpowered solution will be found lacking for half of the cases and will easily cause compatibility problems if its necessary to adopt a more general one in the future.
Yes it needs a lot more work, but I also think @Artazor did an excellent job analyzing and exploring all the aspects that we haven't thought of before. I wouldn't stay we've strayed from the original problem, we only have a better understanding of it.
We may need a better name for it, I'd try but I don't usually get these things right. How about "Object generics"?
@spion, just for correctnes:
awaitObject<p,T[p]>(obj: {...p:Promise<T[p]>}): Promise<{...p:T[p]}>
(you've missed a Promise in output signature) -)
@jods4, I agree with @spion
There are plenty of real-world problems where { ...p: T[p] } is the solution. To name one: react+flux/redux
@spion @Artazor I'm just worried that this is becoming quite complex to specify precisely.
The motivation behind this issue has drifted. Originally it was about supporting APIs that accept a string to denote an object field. Now it's mostly discussing APIs that use objects as maps or records in a very dynamic fashion. Note that if we can kill two birds with one stone I'm all for it.
If we go back to the APIs that take strings problem, the T[p] isn't a complete solution in my opinion (I said why before).
Just for correctness awaitObject should also accept non-Promise properties, at least Bluebird props does. So now we have:
awaitObject<p,T[p]>(obj: { ...p: T[p] | Promise<T[p]> }): Promise<T>
I changed the return type to Promise<T> because I expect this notation to work.
There are other overloads, e.g. one that takes a Promise for such an object (its signature is even more fun). So that means the { ...p } notation needs to be considered a worse match than any other type.
Specifying all of this is going to be hard work. I would say it's the next step if you want to push this forward.
@spion @jods4
I wanted to mention that this feature is not about generics and not about higher kind polymorphic types. This is simply a syntax to reference the type of a property through a containing type (with some "advanced" extensions that are described below), which is not that far from typeof in concept. Example:
type MyType = { abcd: number };
let y: MyType["abcd"]; // Technically this could also be written as MyType.abcd
Now compare to:
type MyType = { abcd: number };
let x: MyType;
let y: typeof x.abcd;
There are two main differences with typeof. Unlike typeof, this applies to types (at least non-primitive ones, a fact that is often omitted here) rather than to instances. In addition (and this is a major thing) it was extended to support using literal string constants (which must be known at compile time) as property path descriptors, and generics:
const propName = "abcd";
let y: MyType[propName];
// Or with a generic parameter:
let y: T[propName];
However technically typeof could have been extended to support string literals as well (this includes the case where x has a generic type):
let x: MyType;
const propName = "abcd";
let y: typeof x[propName];
And with this extension it could also be used to solve some of the target cases here:
function get<T>(propName: string, obj: T): typeof obj[propName]
typeof however is more powerful as it supports indefinite amount of nesting levels:
let y: typeof x.prop.childProp.deeperChildProp
And this one only goes one level. I.e. not planned (as far as I'm aware) to support:
let y: MyType["prop"]["childProp"]["deeperChildProp"];
// Or alternatively
let y: MyType["prop.childProp.deeperChildProp"];
I think the scope of this proposal (if this can even be called a proposal at its level of vagueness) is too narrow. It may help solve a particular problem (though there may be alternative solutions), which seems to make many people very eager to promote it. However it is also consuming valuable syntax from the language. Without a broader plan and design-oriented approach it seems unwise to hastily introduce something that as-of-this-date doesn't even have a clear specification.
Edits: corrected some obvious mistakes in the code examples
I've researched a bit on the typeof alternative:
Future language support for typeof x["abcd"] and typeof x[42] has been approved, and now falls under #6606, which is currently under development (there is a working implementation).
This goes half the way. With these in place, the rest can be done at several stages:
(1) Add support for string literal constants (or even numeric constants - might be useful for tuples?) as property specifiers in type expressions, e.g.:
let x: MyType;
const propName = "abcd";
let y: typeof x[propName];
(2) Allow applying these specifiers to generic types
let x: T; // Where T should extend 'object'
const propName = "abcd";
let y: typeof x[propName];
(3) Allow these specifiers to be passed, and in practice "instantiate" the references, through function arguments (typeof list[0] is planned so I believe this could cover more complex cases like pluck:
function get<T extends object>(obj: T, propertyName: string): typeof obj[propertyName];
function pluck<T extends object>(list: Array<T>, propertyName: string): Array<typeof list[0][propertyName]>;
(object type here is the one proposed at #1809)
Although more powerful (e.g. may support typeof obj[propName][nestedPropName]) it is possible this alternative approach may not cover all the cases described here. Please let me know if there are examples that wouldn't seem to be handled by this (one scenario that comes to mind is when the object instance is not passed at all, however, it is hard for me at this point imagine a case where that would be needed, though I guess that is possible).
Edits: corrected some mistakes in the code
@malibuzios Some thoughts:
- This fixes the API definition but it doesn't help the caller. We still need some kind of
nameoforExpressionat the call site. - It works for
.d.tsdefinitions, but it generally won't be statically inferrable or even verifiable in TS functions/implementations.
The more I think about it, the more Expression<T, U> looks like the solution for those kind of APIs. It fixes the call site problems, the typing of the result and can be inferrable + verifiable in an implementation.
@jods4
You mentioned in a previous comment way above that pluck could be implemented with expressions. Although I did use to be very familiar with C#, I never really experimented with them, so I admit I don't really have a very good understanding of them at this point.
Anyway, just wanted to mention TypeScript supports type argument inference, so instead of using pluck, one can just use map and achieve the same result, which wouldn't even require specifying a generic parameter (it is inferred) and would also give full type checking and completion:
let x = [{name: "John", age: 34}, {name: "Mary", age: 53}];
let result = x.map(obj => obj.name);
// 'result' is ["John", "Mary"] and its type inferred as 'string[]'
Where map (highly simplified for demonstration) is declared as
map<U>(mapFunc: (value: T) => U): U[];
This same inference pattern can be used as a 'trick' to pass any result of an arbitrary lambda (which doesn't even need to be called) to a function and set its return type to it:
function thisIsATrick<T, U>(obj: T, onlyPassedToInferTheReturnType: () => U): U {
return;
}
let x = {name: "John", age: 34};
let result = thisIsATrick(x, () => x.age) // Result inferred as 'number'
Edit: it might look silly to pass it in a lambda here and not just the thing itself! however in more complex cases like nested objects (e.g. x.prop.Childprop) there could be undefined or null references that may error. Having it in a lambda, which is not necessarily called, avoids that.
I admit I'm not very familiar with some of the use cases discussed here. Personally I never felt a need to call a function that takes a property name as string. Passing a lambda (where the advantages you describe also hold) in combination with type argument interface is usually enough to solve many common problems.
The reason I suggested the typeof alternative approach was mostly because that seems to cover about the same use cases and provide the same functionality for what people describe here. Would I use it myself? I don't know, never felt a real need to (it could be simply that I almost never use external libraries like underscore, I almost always develop utility functions by myself, on a needed basis).
@malibuzios True, pluck is a bit silly with lambdas + map now built-in.
In this comment I give 5 different APIs that all take strings -- they are all connected to observing changes.
@jods4 and others
Just wanted to mention that when #6606 is complete, by only implementing stage 1 (allow constant string literals to be used as property specifiers) some of the functionality needed here can be achieved, though not as elegantly as it could (it may require the property name to be declared as a constant, adding an additional statement).
function observeProperty<T, U>(obj: T, propName: string ): Subscriber<U> {
....
}
let x = { name: "John", age: 42 };
const propName = "age";
observeProperty<typeof x, typeof x[propName]>(x, propName);
However, the amount of effort to implement this may be significantly lower than implementing stage 2 and 3 as well (I'm not sure but it's possible that 1 is already covered by #6606). With stage 2 implemented, this would also cover the case where x has a generic type (but I'm not sure if that's really needed though?).
Edit: The reason I used an external constant and not just wrote the property name twice was not only to reduce typing, but also to ensure the the names always match, though this still cannot be use with tools like "rename" and "find all references", which I find to be a serious disadvantage.
@jods4 I'm still looking for a better solution that doesn't make use of strings. I'll try to think what can be done with nameof and its variants.
Here's another idea.
Since string literals are already supported as types, e.g. one can already write:
let x: "HELLO";
One can view a literal string passed to a function as a form of generic specialization
(Edit: these examples was corrected to ensure that s is immutable in the function body, hough const isn't supported at parameter positions at this point (not sure about readonly though).) :
function func(const s: string)
The string parameter type associated with s can be viewed as an implicit generic here (as it can be specialized to string literals). For clarity I will write it more explicitly (though I'm not sure if there's really a need to):
function func<S extends string>(const s: S)
func("TEST");
could internally specialize to:
function func(s: "TEST")
And now this can be used as an alternative way to "pass" the property name, which I feel captures the semantics better here.
function observeProperty<T, S extends string>(obj: T, const propName: S): Subscriber<T[S]>
x = { name: "John", age: 33};
observeProperty(x, nameof(x.age))
Since in T[S], both T, and S are generic parameters. It seems more natural to have two types combined in a type position than mixing run-time and type scope elements (e.g. T[someString]).
Edits: rewritten examples to have an immutable string parameter type.
Since I'm using TS 1.8.7 and not the latest version, I wasn't aware that in more recent versions in
const x = "Hello";
The type of x is already inferred as the literal type "Hello", (i.e.: x: "Hello") which makes a lot of sense (see #6554).
So naturally if there was a way to define a parameter as const (or maybe readonly would also work?):
function func<S extends string>(const s: S): S
Then I believe this could hold:
let result = func("abcd"); // type of 'result' inferred as the literal type "abcd"
Since some of this is rather new and relies on recent language features, I'll try to summarize it as clearly as I can:
(1) When a const (and maybe readonly as well?) string variable receives a value that is known at compile-time, the variable automatically receives a literal type that has the same value (I believe this is a recent behavior that doesn't happen on 1.8.x), e.g.
const x = "ABCD";
Type of x is inferred to be "ABCD", not string!, e.g. one may state this as x: "ABCD".
(2) If readonly function parameters were allowed, a readonly parameter with a generic type would naturally specialize its type to a string literal when it is received as an argument, as the parameter is immutable!
function func<S extends string>(readonly str: S);
func("ABCD");
Here S has been resolved to the type "ABCD", not string!
However, if the str parameter was not immutable, the compiler cannot guarantee that it is not reassigned in the body of the function, thus, the type inferred would be just string.
function func<S extends string>(str: S) {
str = "DCBA"; // This may happen
}
func("ABCD");
(3) It is possible to take advantage of this and modify the original proposal to have the property specifier be a reference to a type, which would need to be constrained to be a derivative of string (in some cases it may be even appropriate to constrain it to singleton literal types only, though there isn't currently really a way to do that), rather than a run-time entity:
function get<T extends object, S extends string>(obj: T, readonly propName: S): T[S]
Calling this would not require explicitly specifying any type arguments, as TypeScript supports type argument inference:
let x = { name: "John", age: 42 };
get(x, "age"); // result type is inferred to be 'number'
// or for stronger type safety:
get(x, nameof(x.age)); // result type is inferred to be 'number'
Edits: corrected some spelling and code mistakes. Note: a generalized and extended version of this modified approach is now also tracked in #7730.
Here is another use of type property type (or "indexed generics" as I like to call them lately) that came up in a discussion with @Raynos
We can already write the following general checker for arrays:
function tArray<T>(f:(t:any) => t is T) {
return function (a:any): a is Array<T> {
if (!Array.isArray(a)) return false;
for (var k = 0; k < a.length; ++k)
if (!f(a[k])) return false;
return true;
}
}
function tNumber(n:any): n is number {
return typeof n === 'number'
}
var isArrayOfNumber = tArray(tNumber)
function test(x: {}) {
if (isArrayOfNumber(x)) {
return x[x.length - 1].toFixed(2); // this type checks
}
}
Once we have indexed generics, we would also be able to write a general checker for objects:
function tObject<p, T[p]>(checker: {...p: (t:any) => t is T[p]}) {
return function(obj: any): obj is {...p: T[p] } {
for (var key in checker) if (!checker[key](obj[key])) return false;
return true;
}
}
which together with the primitive checkers for string, number, boolean, null and undefined would let you write things like this:
var isTodoList = tObject({
items: tArray(tObject({text: tString, completed: tBoolean})),
showCompleted: tBoolean
})
and have it result with the right runtime checker and compile time type guard, at the same time :)
Has anybody done any work on this yet, or is it on anybody's radar? This will be a major improvement to how many standard libraries can use typings, including the likes of lodash or ramda and many database interfaces.
@malibuzios I believe you are approaching @Artazor 's suggestion :)
To address your concerns:
function func<S extends string>(readonly str: S): T[str] {
...
}
This would be
function func<S extends string, T[S]>(str: S):T[S] { }
This way, the name would be locked to the most specific type (a string constant type) when called with:
func("test")
The type S becomes "test" (not string). As such str cannot be reassigned a different value. If you tried that, e.g.
str = "other"
The compiler could produce an error (unless there are variance soundness issues ;))
Instead of just getting the type of one property I would like to have the option to get an arbitrary super type of type.
So my suggestion is to add the following syntax: Instead of just having T[prop], I would like to add the syntax T[...props]. Where props must be an array of members of T. And the resulting type is a super type of T with members of T defined in props.
I think it would be highly useful in Sequelize — a popular ORM for node.js. For security reasons and for perf reasons, it is wise to just query attributes in a table that you need to use. That often means super type of a type.
interface IUser {
id: string;
name: string;
email: string;
createdAt: string;
updatedAt: string;
password: string;
// ...
}
interface Options<T> {
attributes: (memberof T)[];
}
interface Model<IInstance> {
findOne(options: Options<IInstance>): IInstance[...options.attributes];
}
declare namespace DbContext {
define<T>(): Model<T>;
}
const Users = DbContext.define<IUser>({
id: { type: DbContext.STRING(50), allowNull: false },
// ...
});
const user = Users.findOne({
attributes: ['id', 'email', 'name'],
where: {
id: 1,
}
});
user.id
user.email
user.name
user.password // error
user.createdAt // error
user.updatedAt // error
(In my example it includes the operator memberof, which is what you expect it to be, and also the expression options.attributes which is the same as typeof options.attributes, but I think the typeof operator is redundant in this case, because it is in a position that expects a type.).