从这个数据结构可以看出:
const properties = [
{ name: 'name', type: '' },
{ name: 'age', type: 0 },
{ name: 'sex', type: ['m', 'f'] as const },
{ name: 'username', type: '' }
]
Run Code Online (Sandbox Code Playgroud)
我正在尝试动态地构造以下类型:
type Person = {
name: string;
age: number;
sex: 'm'|'f';
username: string;
}
Run Code Online (Sandbox Code Playgroud)
我知道 TypeScript 可以通过映射其他类型来创建类型。但这里的源对象是一个数组,所以看起来有点棘手。我该怎么做呢?
假设我有一个这样的类,它包含一个值:
class Data<T> {
constructor(public val: T){}
set(newVal: T) {
this.val = newVal;
}
}
const a = new Data('hello');
a.set('world');
// typeof a --> Primitive<string>
Run Code Online (Sandbox Code Playgroud)
到目前为止一切顺利,但现在我想将它限制为一组类型中的一个,让我们说原语:
type Primitives = boolean|string|number|null|undefined;
class PrimitiveData<T extends Primitives> {
constructor(public val: T){}
set(newVal: T) {
this.val = newVal;
}
}
const b = new PrimitiveData('hello');
b.set('world'); // Error :(
Run Code Online (Sandbox Code Playgroud)
最后一行失败,因为bis aPrimitive<'hello'>不是 a Primitive<string>,因此set只会将文字'hello'作为值,这显然不是我想要的。
我在这里做错了什么?不诉诸明确扩大自己的类型(例如:)new Primitive<string>('hello')有什么我可以做的吗?