[英]Generic interface inferring type from object property
I've got an interface I
with the goal of making sure that the property type of val
is the same as the return type of fn
.我有一个接口
I
,目的是确保val
的属性类型与fn
的返回类型相同。
The type in question is restricted to string
or number
.有问题的类型仅限于
string
或number
。
interface I<T extends string | number> {
val: T;
fn: () => T;
}
const x1: I<string> = {
val: "hello",
fn: () => "world",
};
const x2: I<number> = {
val: 3,
fn: () => 4,
};
Is it somehow possible to not having to explicitly set T
and rather infer it?是否有可能不必显式设置
T
而是推断它? So that I could just do:这样我就可以这样做:
// accepted
const x1: I = {
val: "hello",
fn: () => "world",
};
// accepted
const x2: I = {
val: 3,
fn: () => 4,
};
// rejected
const x3: I = {
val: "hello",
fn: () => 4,
};
// rejected
const x4: I = {
val: 3,
fn: () => "world",
};
As far as I know, it is not possible for TS to infer the type for your example.据我所知,TS 不可能为您的示例推断类型。 However, there is a way to achieve similar effects using a helper function:
但是,有一种方法可以使用助手 function 实现类似的效果:
function make<T extends string|number>(input: I<T>) {
return input;
}
// accepted
const x1 = make({
val: "hello",
fn: () => "world",
});
// accepted
const x2 = make({
val: 3,
fn: () => 4,
});
// rejected
const x3 = make({
val: "hello",
fn: () => 4,
});
// rejected
const x4 = make({
val: 3,
fn: () => "world",
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.