我試圖創建一個帶有字串限制的類,但在get scale()函式中出現了錯誤。
class Scaling< T extends string> {
_scale = ""。
constructor(props: T) {
this._scale = props;
}
setScale(scale: T) {
this._scale = scale。
}
get scale(): T {
return this._scale。
}
型別'string'不能被分配給型別'T'。 'string'是可以被分配到 型別'T'的約束,但是'T'可以被實體化為約束'string'的一個不同的子型別。 不同的子型別的約束'string'。 }
uj5u.com熱心網友回復:
你應該從get scale()中洗掉明確的。T回傳型別。T
因為在初始化期間,T被推斷為引數的字面型別。
請看這個例子:
class Scaling< T extends string> {
_scale = ""。
constructor(props: T) {
this._scale = props;
}
setScale(scale: T) {
this._scale = scale。
}
get scale(): T {
return this._scale。
}
}
//T推斷為字面 "hello"。
const result = new Scaling('hello')
因此,當你想回傳T時,應該是"hello"。
在你的例子中,它不可能是"hello",因為_scale的默認值是空字串,因此它被推斷為一個字串。
let str = ' '
//Type 'string' is not assignable to type '"hello"'
const sameCase=()。'hello' => str
你不能用T作為_scale的顯式型別,因為_scale是可變的,而型別是不可變的。
這就是為什么從get scale回傳T型別是不安全的
即使我從get scale中洗掉了T,當const result = new Scaling("hello"); result.setScale("other")時,我仍然得到一個錯誤
。
我的錯,沒有檢查。
為了使這個類成為通用的,我們需要將推論的T從更具體的型別轉換為更廣泛的型別。
type Infer<T> = T extends infer R ? R : never
class Scaling<T extends string> {
_scale = ""。
constructor(props: Infer<T>/span>) {
this._scale = props;
}
setScale(scale: T) {
this._scale = scale。
}
get scale() {
return this._scale。
}
}
//T推斷為字面意思 "hello"。
const result = new Scaling('hello') // ok
result.setScale('123') // ok
uj5u.com熱心網友回復:
_scale成員實際上應該是T型別。例如:
class Scaling< T extends string> {
_scale = "" as T。
constructor(props: T) {
this._scale = props;
}
setScale(scale: T) {
this._scale = scale。
}
get scale(): T {
return this._scale。
}
uj5u.com熱心網友回復:
_scale不應該是T的型別嗎?所以你要用冒號(:)來分配
class Scaling< T extends string> {
_scale: T。
constructor(props: T) {
this._scale = props;
}
setScale(scale: T) {
this._scale = scale。
}
get scale(): T {
return this._scale。
}
用法是:
const scaling = new Scaling('Hello World')
console.log(scaling)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/318601.html
標籤:
上一篇:泛型介面中的泛型原型函式?Array<T>.GroupBy<K>(prop):{key:K,array:T[]}[]
