給定這個例子:
type A = (arg?: string) => void
const myObject : { a: A } = {
a: (arg: "yes" | "no") => { console.log(1)}
}
我收到一個錯誤:
Type 'string | undefined' is not assignable to type '"yes" | "no"'.
Type 'undefined' is not assignable to type '"yes" | "no"'
即使我arg?: "yes" | "no"成功了,也會回傳:
Type 'string | undefined' is not assignable to type '"yes" | "no" | undefined
Type 'string' is not assignable to type '"yes" | "no" | undefined'
我想知道是否有任何方法可以arg在可選引數時更精確地鍵入(“yes”|“no”而不是字串)。假設我無法觸摸type A
uj5u.com熱心網友回復:
這可以:
const a1: 'yes' | 'no' = 'yes'
const a2: string | undefined = a1
這不是:
const b1: string | undefined = 'yes'
const b2: 'yes' | 'no' = b1 // Error: Type 'string' is not assignable to type '"yes" | "no"'
在函式中:
type A = (arg?: string) => void
const f: A = (arg: 'yes' | 'no') => { console.log(arg.toUpperCase()) }
// Error: Type '(arg: 'yes' | 'no') => void' is not assignable to type 'A'
如果我們忽略 TypeScript 錯誤,則可能會出現運行時錯誤:
const f: A = ((arg: 'yes' | 'no') => { console.log(arg.toUpperCase()) }) as A
f(undefined) // Runtime Error!
arg?: "yes" | "no"不是答案,因為仍然存在風險:
const f: A = ((arg?: 'yes' | 'no') => {
if (arg) {
console.log(arg[1].toUpperCase()) // log second char as upper case
}
}) as A
f('A') // Runtime Error!
uj5u.com熱心網友回復:
你有一個選擇。選項1:
type A = (arg?: 'yes'|'no') => void
const myObject : { a: A } = {
a: (arg?: 'yes'|'no') => { console.log(1)}
}
選項 2:
type A = (arg?: string) => void
const myObject : { a: A } = {
a: (arg?: string) => { console.log(1)}
}
uj5u.com熱心網友回復:
合約(介面)由型別 A 決定。
您不能分配更窄(或不同)的東西,因為當您呼叫時,myObject.a您將使用A. 所以你分配的東西必須接受定義的形狀A。
myObject.a('foo') // valid, as 'foo' is a string, as per A's interface
允許分配除Ato以外的東西myObject.a所提供的函式可能會接收到一些意外的東西,這會破壞型別安全的目的。
如果您不能更改 的定義A,那么您將必須myObject.a使用與 相同的介面來實作分配給的函式A,并進行運行時檢查以查看提供的 arg 是否符合“是” | “不”。一個簡單的比較就足夠了,或者如果它變得更復雜,你可以考慮一個型別保護,這將縮小塊剩余部分的范圍。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/466990.html
標籤:打字稿
上一篇:在打字稿中推斷函式引數型別
