interface MyProps {
x: number;
y: string;
}
const myVar: MyProps = {
x: 1,
y: '2',
};
function getMyValue(prop?: keyof MyProps) {
if (prop) {
return myVar[prop];
}
return myVar;
}
const x = getMyValue('x');
const y = getMyValue('y');
const val = getMyValue();
現在,我得到的型別x就是string | number | MyProps,但我希望x是number,y是string和val是MyProps。那么,該怎么做呢?
uj5u.com熱心網友回復:
您必須使用泛型和函式多載:
interface MyProps {
x: number;
y: string;
}
const myVar: MyProps = {
x: 1,
y: '2',
};
function getMyValue<Prop extends keyof MyProps = keyof MyProps>(prop: Prop): MyProps[Prop]
function getMyValue(): MyProps
function getMyValue<Prop extends keyof MyProps = keyof MyProps>(prop?: Prop): MyProps[Prop] | MyProps {
if (prop) {
return myVar[prop];
}
return myVar;
}
打字稿游樂場
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/407782.html
標籤:
上一篇:強制泛型型別的交集以擴展給定型別
下一篇:更改下拉值時設定值和觸發動作
