我想将一个对象类型映射到一个子类型,该子类型只包含值属于特定类型的键。
例如,像ExtractNumeric<T>, where
ExtractNumeric<{ str: string, num: number }>应该等价于类型:{ num: number }
我试过这个,但它不起作用:
type ExtractNumeric<T> = { [k in keyof T]: T[k] extends number ? T[k] : never }
此代码段引发类型错误:
let obj: ExtractNumeric<{ str: string, num: number }> = { num: 1 }
因为虽然str键期望值为never,但编译器会抱怨它的缺失。
这是代码
class A {
x = 0;
y = 0;
visible = false;
render() {
return 1;
}
}
type RemoveProperties<T> = {
readonly [P in keyof T]: T[P] extends Function ? T[P] : never//;
};
type JustMethodKeys<T> = ({ [P in keyof T]: T[P] extends Function ? P : never })[keyof T];
type JustMethods<T> = Pick<T, JustMethodKeys<T>>;
type IsValidArg<T> = T extends object ? keyof T extends never ? false : true : true;
type Promisified<T extends Function> = …Run Code Online (Sandbox Code Playgroud) 我有一个这样定义的接口和类:
interface Foo {
constructor: typeof Foo;
}
class Foo {
static bar = 'bar';
constructor(data: Partial<Foo>) {
Object.assign(this, data);
}
someMethod() {
return this.constructor.bar;
}
prop1: string;
prop2: number;
}
Run Code Online (Sandbox Code Playgroud)
接口是this.constructor强类型所必需的。但是,它破坏了我将普通对象传递给类构造函数的能力:
const foo = new Foo({ prop1: 'asdf', prop2: 1234 });
// Argument of type '{ prop1: string; prop2: number; }' is not assignable to parameter of type 'Partial<Foo>'.
// Types of property 'constructor' are incompatible.
// Type 'Function' is not assignable to type 'typeof Foo'.
// …Run Code Online (Sandbox Code Playgroud)