return type narrowing from array of predicates

classes with static check methods. wanted to find the
matching one and return to it in wrap method.

this architecture perfectly suits for my need of OOP-ifying.
here is the way that I used to do it in JavaScript:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class A {
static check = arg => typeof arg == "number"
constructor(arg) { this.value = arg}
log = () => console.log("A/", this.value)
}
class B {
static check = arg => typeof arg == "string"
constructor(arg) { this.note = arg }
log = () => console.log("B/", this.note)
}
function wrap(arg, classes) {
for (const Class of classes)
if (Class.check(arg))
return new Class(arg)
}
const classes = [A, B]
wrap("adaptive", classes).log()
wrap(999, classes).log()</code>
<code>class A { static check = arg => typeof arg == "number" constructor(arg) { this.value = arg} log = () => console.log("A/", this.value) } class B { static check = arg => typeof arg == "string" constructor(arg) { this.note = arg } log = () => console.log("B/", this.note) } function wrap(arg, classes) { for (const Class of classes) if (Class.check(arg)) return new Class(arg) } const classes = [A, B] wrap("adaptive", classes).log() wrap(999, classes).log()</code>
class A {
    static check = arg => typeof arg == "number"
    constructor(arg) { this.value = arg}
    log = () => console.log("A/", this.value)
}

class B {
    static check = arg => typeof arg == "string"
    constructor(arg) { this.note = arg }
    log = () => console.log("B/", this.note)
}

function wrap(arg, classes) {
    for (const Class of classes) 
        if (Class.check(arg))
            return new Class(arg)
}

const classes = [A, B]

wrap("adaptive", classes).log()
wrap(999, classes).log()

lately, I thought maybe TypeScript could help me with that. what
I expected was that the wrap call would indicate the return
value (since it’s all about types with no logic)

unfortunately, it was not the case. the closest I could get was that:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>type PayloadA = number
type PayloadB = string
type PayloadGeneric = PayloadA | PayloadB
class A {
static check(arg:PayloadGeneric): arg is PayloadA {
return typeof arg == "number"
}
value: number
constructor(arg: PayloadA) { this.value = arg}
log = () => console.log("A/", this.value)
}
class B {
static check(arg:PayloadGeneric): arg is PayloadB {
return typeof arg == "string"
}
note: string
constructor(arg: PayloadB) { this.note = arg}
log = () => console.log("B/", this.note)
}
function wrap(arg: PayloadGeneric) {
if (A.check(arg)) { // understands that arg is number
return new A(arg) // and that arg is suitable for PayloadA
}
if (B.check(arg)) { // understands that arg is string
return new B(arg) // and that arg is suitable for PayloadB
}
}
const instanceA = wrap(999) // but here it doesn't understand the type
const instanceB = wrap("adaptive") // neither here
</code>
<code>type PayloadA = number type PayloadB = string type PayloadGeneric = PayloadA | PayloadB class A { static check(arg:PayloadGeneric): arg is PayloadA { return typeof arg == "number" } value: number constructor(arg: PayloadA) { this.value = arg} log = () => console.log("A/", this.value) } class B { static check(arg:PayloadGeneric): arg is PayloadB { return typeof arg == "string" } note: string constructor(arg: PayloadB) { this.note = arg} log = () => console.log("B/", this.note) } function wrap(arg: PayloadGeneric) { if (A.check(arg)) { // understands that arg is number return new A(arg) // and that arg is suitable for PayloadA } if (B.check(arg)) { // understands that arg is string return new B(arg) // and that arg is suitable for PayloadB } } const instanceA = wrap(999) // but here it doesn't understand the type const instanceB = wrap("adaptive") // neither here </code>
type PayloadA = number
type PayloadB = string
type PayloadGeneric = PayloadA | PayloadB

class A {
    static check(arg:PayloadGeneric): arg is PayloadA {
        return typeof arg == "number"
    }
    value: number
    constructor(arg: PayloadA) { this.value = arg}
    log = () => console.log("A/", this.value)
}

class B {
    static check(arg:PayloadGeneric): arg is PayloadB {
        return typeof arg == "string"
    }
    note: string
    constructor(arg: PayloadB) { this.note = arg}
    log = () => console.log("B/", this.note)
}

function wrap(arg: PayloadGeneric) {
    if (A.check(arg)) {   // understands that arg is number
        return new A(arg) // and that arg is suitable for PayloadA
    } 
    if (B.check(arg)) {   // understands that arg is string
        return new B(arg) // and that arg is suitable for PayloadB
    }
}

const instanceA = wrap(999) // but here it doesn't understand the type
const instanceB = wrap("adaptive") // neither here

(I know PayloadA and PayloadB may look silly since they’re just
number and string but the whole point is about having custom interfaces
and predicates. number and string is just for the example and wrapping them
into a type demonstrates my purpouse better)

look wrap can only accept PayloadA or PayloadB. inside, we have 2 ifs.
one checks for PayloadA and understands and returns, the other checks
for PayloadB and again understands well and returns. but TypeScript
doesn’t stop there and continues reading the rest, like it may get executed.
even thinks it may return undefined since I’m not handling the default
return, but logically, I do – I only accept A or B and handled both. so,

I’m handling all the cases but TypeScript doesn’t get it. how do I fix it? I want something like return type narrowing.

and please don’t tell me “just put return type A | B” I don’t wanna hardcode
cuz the given list can change. I may put classes that none of their check method
matches, in this case I’d like to see that the return type is going to be undefined.
or I put one that matches, then I’d like to see what the return type is gonna be.

thanks in advance

6

TS currently doesn’t support following control flow to infer a narrowed return type. The situation will change with TS 5.8 to some degree. As a current solution you could try function overloading:

Playground

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>function wrap(arg: PayloadA): A;
function wrap(arg: PayloadB): B;
function wrap(arg: PayloadGeneric) {
if (A.check(arg)) { // understands that arg is number
return new A(arg) // and that arg is suitable for PayloadA
}
if (B.check(arg)) { // understands that arg is string
return new B(arg) // and that arg is suitable for PayloadB
}
throw new Error('arg is not of allowed type string|number')
}
</code>
<code>function wrap(arg: PayloadA): A; function wrap(arg: PayloadB): B; function wrap(arg: PayloadGeneric) { if (A.check(arg)) { // understands that arg is number return new A(arg) // and that arg is suitable for PayloadA } if (B.check(arg)) { // understands that arg is string return new B(arg) // and that arg is suitable for PayloadB } throw new Error('arg is not of allowed type string|number') } </code>
function wrap(arg: PayloadA): A;
function wrap(arg: PayloadB): B;
function wrap(arg: PayloadGeneric)  {
    if (A.check(arg)) {   // understands that arg is number
        return new A(arg) // and that arg is suitable for PayloadA
    } 
    if (B.check(arg)) {   // understands that arg is string
        return new B(arg) // and that arg is suitable for PayloadB
    }
    throw new Error('arg is not of allowed type string|number')
}

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật