typescript 对象类型的泛型类型?

jhkqcmku  于 2022-12-19  发布在  TypeScript
关注(0)|答案(1)|浏览(134)

我在写一个类,在构造函数中我可以传递一个参数,它是一个对象数组:

class MyClass {
    constructor(p: Array<CustomObject>) {
        // TODO
    }
}

现在,类并不重要,重要的是CustomType类型脚本类型,我想创建一个基于单个属性值的“动态”类型(或者更好,具有动态属性)。
我知道在typescript中我们可以使用泛型来实现这样的函数:

function foo<T extends 'bar' | 'baz'>(x: T) {
    // TODO
}

这样我们就不用每次使用函数时都定义泛型了,我们只需要调用它,传递参数,然后typescript就能推断出类型,但是对象呢?
我需要这样的东西:

type CustomObject<T extends 1 | 2> = {
    x: T    // Here i need typescript to infer the type
}

为了像这样使用它:

const obj: CustomObject = {
    x: 1    // Now typescript knows the type without explicitly setting it as a generic
}

到目前为止,我尝试了上面的例子(当然失败了),显然类的方法:

class CustomObject<T extends 1 | 2> {
    constructor(init: { x: T }) {
        // TODO
    }
}

const obj = new CustomObject({ x: 1 }) // This way typescript knows the type and i don't have to pass a generic

我只是想知道是否有一种方法可以不使用类来定义动态对象类型。

pn9klfpd

pn9klfpd1#

你可以用同样的方法,但是用函数代替类

function CustomObject<T extends 1 | 2>(init: { x: T }) {
  return init;
}

const obj = CustomObject({ x: 1 })

相关问题