5

In typescript, we can use index types like this :

interface Dummy {
    name: string;
    birth: Date;
}

function doSomethingOnProperty<T, K extends keyof T>(o: T, name: K): void {
    o[name]; // do something, o[name] is of type T[K]
}

var dummy = { name: "d", birth: new Date() };

doSomethingOnProperty(dummy, "name");

Question :

How to add a generic constraint to only accept name of property of certain type (is it possible ?) :

// Generic constraint on T[K] ? T[K] must be of type Date
function doSomethingOnDATEProperty<T, K extends keyof T>(o: T, name: K): void {
    o[name];
}

// should not compile,
// should accept only the name of propery "birth" which is of type date
doSomethingOnDATEProperty(dummy, "name");
2
  • 1
    I answered a very similar question today stackoverflow.com/a/49797062/3848 Commented Apr 12, 2018 at 17:57
  • 1
    @Motti while similar your solution from that question has a problem o[name] will not be typed as FancyType that was not an issue there as it was not required, here the requirement is that you can access the field of the object in a typed way Commented Apr 12, 2018 at 18:00

1 Answer 1

7

You can do the following:

function doSomethingOnDATEProperty<T extends { [P in K]: Date }, K extends keyof T>(o: T, name: K): void {
    let d = o[name]; // do something, o[name] is of type T[K] but also Date
    d.getFullYear(); // Valid
}

var dummy = { name: "d", birth: new Date() };

doSomethingOnDATEProperty(dummy, "birth");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.