使用新的,我可以按以下方式过滤出类型的键。
// Filter out all keys of `T` that do not exist in `U`
type IntersectKeys<T, U> = {
[K in keyof T as K extends keyof U ? K : never]: T[K];
};
// e.g., IntersectKeys<{ foo: string; bar: number}, { foo: never }> === { foo: string }
但是,当我在泛型中使用这种类型时,TypeScript似乎完全
我正在尝试找到一种方法来告诉TypeScript的编译器,值是(深呼吸)泛型类型的键,如果应用于该类型的对象,将产生特定类型的属性。我知道这句话真的很让人困惑,所以这里有一个具体的例子。
const obj: T = an object of type T;
const key: KeysMatching<T, U> = a key that matches `typeof T[key] === U`;
const attribute = obj[key];
在这里,我希望attribute是U类型,或者可以赋值给U类型。
我受到TypeScript文档中提供的的启发,尝试使用中建
以下代码会导致错误,因为根据TypeScript,类型Pick<Test<T>, Exclude<keyof T, "someKey">>不能赋值给T。当我推断这种类型时,它应该被赋值给T,有没有办法让TypeScript同意我的观点?或者这只是突破了TypeScript中泛型类型的界限,因为不是动态类型的变体可以正确编译。 type Test<T = {}> = T & {
someKey: string
};
function extract<T>(props: Test<T>): T
是否可以将typescript联合类型与表单对象类型的值重新映射? 例如我在mid中的: type Union = 'item-type' | 'category';
type Special = {
'item-type': 'itemType';
};
type RemapedValue = [... some realy awesome typescript ...] // => 'itemType' | 'category'
我一直在研究并尝试将现有项目(从Node.js)转换为TypeScript。
对于上下文,我使用的是http-status包()
我试图将变量传递到它们的默认导出中,但是它得到了一个错误:
import status = require("http-status");
status.OK; // this works
status["OK"] // this also works
let str = "OK";
status[str]; // error
错误:
元素隐式具有'any‘类型,因为类型'string’的表达式不能
在TypeScript中,私有属性被认为是类型的形状(或接口)的一部分。
class Person {
constructor(private name: string, public age: number) { }
}
const p: Person = { age: 42 };
// Error: Property 'name' is missing.
这是有效的,因为TypeScript需要跟踪隐私。
class Person {
constructor(private name: string, public age: number) { }
equals
在普通的JavaScript中,我们可以使用变量读取对象的属性值。
也就是说,这是有效的:
let obj = { a: 100, b: 'Need help with TypeScript', c: new Date() };
let prop = 'b';
console.log( obj[prop] ); // Need help with TypeScript
但是,下面的TypeScript注释声明prop为字符串将导致指示的索引错误。
let obj: object = { a: 100, b: 'Need help with TypeSc
Pick类型包括在TypeScript中。它的实施情况如下:
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};
如何编写PickByValue类型以使下列工作:
type Test = {
includeMe: 'a' as 'a',
andMe: 'a' as 'a',
butNotMe: 'b' as 'b',
orMe: 'b' as 'b'
};
type Inclu