我試圖鍵入函式的引數,以便編譯器可以正確地對兩者進行檢查。為了演示,假設我有需要輸入的型別Item和函式f:
type Item = {
Book: { price: number };
Box: { weight: number };
}
const f = (param1, param2): void => { ... }
我想要實作的是:
// correct: both name and related attributes are right
f('Book', { price: 20 })
f('Box', { weight: 10 })
// error: 'Chair' is not a 'Book' or 'Box'
f('Chair', { price: 20 })
// error: 'Book' should be provided with a price
f('Book', { weight: 20 })
f('Book', { foo: 20 })
我嘗試輸入f如下:
const f = (param1: keyof Item, param2: Item[keyof Item]): void => { ... }
主要是有效的,除了
f('Box', { price: 200 })
沒有引發編譯器錯誤。
我應該如何按照描述鏈接兩個引數?
uj5u.com熱心網友回復:
所以你想要解決這個問題的方法是param2基于param1. 現在您所說的是param1Item 的某個鍵,并且是與任何鍵param2匹配的 item 的某個值,而不是鍵 param1。
相反,你想要的是param2成為typeof Item[param2]. 我會用泛型來做到這一點。
type Item = {
Book: {price: number};
Box: {weight: number;}
};
const f = <K extends keyof Item, E extends Item[K]>(param1: K, param2: E): void => {}
f('Box', {price: 5})
這會引發以下錯誤:
Argument of type '{ price: number; }' is not assignable to parameter of type '{ weight: number; }'.
Object literal may only specify known properties, and 'price' does not exist in type '{ weight: number; }'.
但這不會:
f('Box', {weight: 5})
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/419258.html
標籤:
