打字稿:在接口范围内推断类型而不扩展

Typescript: Infer type without extends within interface scope

我不确定这是否足够声明,但我需要在接口范围内推断类型并在与方法参数相同的范围内使用它。这是一个简单的例子

interface Prop {
    x: infer U,
    // ^^^^^^^ store type coming from 'x'
    validate: (x: U) => U
    //            ^ use type
}

interface IState {
    [key: string]: Prop
}

和用例

const state:IState = {
    asString: {
        x: '',
        validate: value => value + ' is string',
        //        ^^^^^ string
    },
    asBoolean: {
        x: true,
        validate: value => !value;
        //        ^^^^^ boolean
    }
}

这可能吗?

这不是您想要的,但您可以这样做:

interface Prop<U> {
    x: U,
    validate: (x: U) => U
}

function makeProp<U>(x: U, validate: (x: U) => U): Prop<U> {
    return { x, validate }
}

const state = {
    asString: makeProp('', value => value + ' is string'),
    asBoolean: makeProp(true, value => !value)
}
// Here, 'state' is of type: { asString: Prop<string>, asBoolean: Prop<boolean> }