Typescript come digitare il resto dei parametri in object
Nov 26 2020
function test(data){
console.log(data)
}
test({comments: 'hi', eat: true, sleep: true})
Nella funzione test, sono sicuro che apparirà l'argomento commento, dove come per altri argomenti, le proprietà potrebbero essere dinamiche ma il valore sarà di tipo booleano,
test({comments: 'hi', drink: true, sleep: true})
considerando questa situazione, come devo digitare correttamente i dati? Ho provato qualcosa di simile, ma sembra sbagliato
function(data: {data: {comments: string, [key: string]: boolean})
Risposte
1 НиколайГольцев Nov 26 2020 at 17:55
Posso suggerirti una sorta di soluzione alternativa:
function test<T extends {
[key: string]: any;
}>(data: { comments: unknown } & { [key in keyof T]: key extends "comments" ? string : boolean }) {
const comments = data.comments as string;
console.log(comments);
console.log(data.eat);
console.log(data.sleep);
}
test({comments: "hi"}); // works
test({comments: "hi", eat: true}); // works
test({comments: true}); // doesn't works
test({comments: 5}); // doesn't works
test({comments: "hi", eat: "true"}); // doesn't works
test({comments: "hi", eat: 5}); // doesn't works
Ha digitato bene al di fuori del corpo della funzione, ma nel corpo della funzione per digitare data.commentscorrettamente dovresti aggiungere un po 'di restringimento.