在typescript中,我们可以使用这样的索引类型:
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");
Run Code Online (Sandbox Code Playgroud)
问题:
如何添加通用约束只接受某种类型的属性名称(是否可能?):
// 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 …Run Code Online (Sandbox Code Playgroud) 我目前正在测试Lucene.Net,这是适合我的需要,但我已经看到了 这个最近的文章在开发邮件列表(无答案)...你认为这是不安全的,开始与这个库深化发展?我以为它被广泛使用?
在 typescript 2.2 中,当strictNullChecks选项为 true 时,如何声明可为 null 的对象文字变量:
let myVar = { a: 1, b: 2 };
myVar = null; // Error can not assign null
Run Code Online (Sandbox Code Playgroud)
我发现的唯一方法是:
// Verbose
let myVar: { a: number; b: number; } | null = { a: 1, b: 2 };
// Bad, same as having no type
let myVar: any| null = { a: 1, b: 2 };
Run Code Online (Sandbox Code Playgroud)