我有以下代码片段:
// Library code
type Forced = {
name: string;
}
const funcExample = <T extends Forced,>(
values: T[],
defaultValue: (name: string) => T,
): T[] => {
// Do some operations...
const result = values.map( (value) => {
// Yay, I can access my .name attribute on a Generic.
// That's what I want
if (value.name === "wrong_condition_that_leads_to_default") {
const res = defaultValue(value.name)
return res;
}
const res2 = {...value}
return res2;
})
return result;
}
// User code
type Animal = {
name: string,
parent: string,
}
const animals: Animal[] = [
{name: "A", parent: "Y"},
{name: "B", parent: "X"},
{name: "C", parent: "Z"},
]
const myVar = funcExample(
animals,
(name) => {
const t = {
name: name,
parent: "foo",
};
return t;
}
)
// Type of myVar is...
// const myVar: {
// name: string;
// parent: string;
// }[]
// I want it to be...
// const myVar: Animal[]
我已经找到了一个解决方案,它包括调用我的泛型funcExample
,并在回调中指定正确的类型,例如...
const myVar = funcExample(
animals,
(name) => {
const t: Animal = {
name: name,
parent: "foo",
};
return t;
}
)
// Now the type is great, automaticly.
// const myVar: Animal[]
有没有一种方法可以让它自动映射?
我今天想要解决的问题是,我想让TypeScrip使以下错误不可能发生:定义一个不尊重我在defaultValue: (name: string) => T
类型签名中提供的签名的回调.
编辑:
例如,如果我没有实现键parent: string
,这就不会抛出错误.但我希望它抛出一个错误.
const myVar = funcExample(
animals,
(name) => {
const t = {
name: name,
};
return t;
}
)