'How do I specify the type of the next parameter based on the type of the previous parameter? [duplicate]
I have an interface like
type messageType = 'msg' | 'peerCommon'
type peerCommonMessageType = 'hangUp' | 'disconnect' | 'inviteReject' | 'partyReject'
interface reciveMessage {
type: messageType
message: string | peerCommonMessageType
}
I want the type of message to be string when the Type is msg, and the type of message to be peerCommonMessageType when the Type is peerCommon, how do I modify the above code?
Solution 1:[1]
Use a discriminated union:
type messageType = 'msg' | 'peerCommon'
type peerCommonMessageType = 'hangUp' | 'disconnect' | 'inviteReject' | 'partyReject'
interface msgMessage {
type: 'msg';
message: string;
}
interface peerCommonMessage {
type: 'peerCommon'
message: peerCommonMessageType
}
type reciveMessage = msgMessage | peerCommonMessage;
// Passes
const test1: reciveMessage = {
type: 'msg',
message: 'any string'
}
// Fails
const test2: reciveMessage = {
type: 'peerCommon',
message: 'any string'
}
// Passes
const test3: reciveMessage = {
type: 'peerCommon',
message: 'hangUp'
}
Solution 2:[2]
I handled the same thing. Try this on MainVC:
class MainVC: UIViewController, SecondVCDelegate {
func passData(text: String) {
// do stuff
}
@IBAction func openNextVC(_ sender: Any) {
guard let secondController = self.storyboard?.instantiateViewController(withIdentifier: "AddGroupVC") as? AddGroupVC else { return }
secondController.delegate = { [weak self] in
print("call your delegates here")
}
self.navigationController?.present(secondController, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
On second View Controller, call the delegates in viewWillDisappear :
class SecondVC: UIViewController {
var delegate: SecondVCDelegate?
@IBAction func save(_ sender: Any) {
// do stuff
self.dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillDisappear(_ animated: Bool) {
self.delegate
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Daniel |
| Solution 2 | Taimoor Arif |
