我不确定这是否足够声明,但是我需要推断接口范围内的类型并在与方法参数相同的范围内使用它。这是简单的例子
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
}
}
这有可能吗?
答案 0 :(得分:1)
这不是您想要的,但是您可以做到:
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> }