我在 Typescript 將默認值傳遞給類似于pickfrom lodash的函式時遇到了問題。
該函式接受一個已知(非通用)介面的物件和一組從物件中選擇和回傳的鍵。
函式的常規(無默認引數)宣告正常作業,但是,我似乎無法將陣列設定為選擇要選取的屬性的引數的默認值。
interface Person {
name: string;
age: number;
address: string;
phone: string;
}
const defaultProps = ['name', 'age'] as const;
function pick<T extends keyof Person>(obj: Person, props: ReadonlyArray<T> = defaultProps): Pick<Person, T> {
return props.reduce((res, prop) => {
res[prop] = obj[prop];
return res;
}, {} as Pick<Person,T>);
}
const testPerson: Person = {
name: 'mitsos',
age: 33,
address: 'GRC',
phone: '000'
};
如果洗掉默認值,= defaultProps它會成功編譯,并且從示例呼叫中回傳的型別也是正確的,例如:const testPick = pick(testPerson, ['name']);
但是,設定默認值會產生以下錯誤:
Type 'readonly ["name", "age"]' is not assignable to type 'readonly T[]'.
Type '"name" | "age"' is not assignable to type 'T'.
'"name" | "age"' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'keyof Person'.
Type '"name"' is not assignable to type 'T'.
'"name"' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'keyof Person'.
如何成功將默認值傳遞給props引數?
打字稿游樂場鏈接在這里
uj5u.com熱心網友回復:
您可以多載pick功能:
interface Person {
name: string;
age: number;
address: string;
phone: string;
}
const defaultProps = ['name', 'age'] as const;
type DefaultProps = typeof defaultProps;
function pick(obj: Person): Pick<Person, DefaultProps[number]>
function pick<Prop extends keyof Person, Props extends ReadonlyArray<Prop>>(obj: Person, props: Props): Pick<Person, Props[number]>
function pick<T extends keyof Person>(obj: Person, props = defaultProps) {
return props.reduce((res, prop) => ({
...res,
[prop]: obj[prop]
}), {} as Pick<Person, T>);
}
const testPerson = {
name: 'mitsos',
age: 33,
address: 'GRC',
phone: '000'
};
const result = pick(testPerson) // Pick<Person, "name" | "age">
const result2 = pick(testPerson, ['phone']) // Pick<Person, "phone">
const result3 = pick(testPerson, ['abc']) // expected error
操場
您可以pick在我的文章和其他答案中找到更高級的型別:
First , second , third
uj5u.com熱心網友回復:
類似的東西?更新了 TS 游樂場。
const defaultProps: ReadonlyArray<keyof Person> = ['name', 'age'] as const;
function pick<T extends keyof Person>(obj: Person, props: ReadonlyArray<T> = (defaultProps as ReadonlyArray<T>)): Pick<Person, T> {
更新:
TS游樂場。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/332672.html
上一篇:Next.js的每頁布局組件無法從Vercel的swr全域配置中獲得價值
下一篇:使用按鈕單擊更改兩個組件的顏色
