簡體   English   中英

如何在Typescript中將默認值設置為具有keyof類型(來自顯式類型)的參數

[英]How to set default value to param that has type keyof (from an explicit type) in Typescript

我在 Typescript 將默認值傳遞給類似於pick from 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參數?

打字稿游樂場鏈接在這里

類似的東西? 更新了 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游樂場

您可以重載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

操場

您可以在我的文章和其他答案中找到更高級的pickFirst , second , third

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM