Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript index types, how to add constraint on T[K]

Tags:

typescript

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");
like image 722
PlageMan Avatar asked Apr 12 '18 17:04

PlageMan


1 Answers

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");
like image 56
Titian Cernicova-Dragomir Avatar answered Oct 19 '22 17:10

Titian Cernicova-Dragomir